On my screen I need to add three images for that I have three separate buttons
code: here EasyImagePicker is my custom imagepicker.. but with my below code if I select any one image from imagepicker then it's adding in all three images
class EditProfileImagesVC: UIViewController {
private var imagePicker : EasyImagePicker?
private var imagePicker1 : EasyImagePicker?
private var imagePicker2 : EasyImagePicker?
#IBOutlet weak var profilePicImage: UIImageView!
#IBOutlet weak var leftProfilePicImg: UIImageView!
#IBOutlet weak var rightProfilePicImg: UIImageView!
override func viewDidLoad() {
super.viewDidLoad()
imagePicker = EasyImagePicker(presentationController: self, delegate: self)
imagePicker1 = EasyImagePicker(presentationController: self, delegate: self)
imagePicker2 = EasyImagePicker(presentationController: self, delegate: self)
}
#IBAction func profilePicBtn(_ sender: UIButton) {
imagePicker?.present(from: sender, mediaType: .images, onViewController: self)
}
#IBAction func leftProfileBtn(_ sender: UIButton) {
imagePicker1?.present(from: sender, mediaType: .images, onViewController: self)
}
#IBAction func rightProfileBtn(_ sender: UIButton) {
imagePicker2?.present(from: sender, mediaType: .images, onViewController: self)
}
}
extension EditProfileImagesVC : EasyImagePickerDelegate{
func didSelect(image: UIImage?, video: URL?, fileName: String?) {
if let img = image{
profilePicImage.image = img
}
if let img1 = image{
leftProfilePicImg.image = img1
}
if let img2 = image{
rightProfilePicImg.image = img2
}
}
}
how to select three different images for three images using imagepicker.. please do guide me
The reason is there is no thing here that can differentiate which button is clicked , hence result set to all imageviews
func didSelect(image: UIImage?, video: URL?, fileName: String?) {
if let img = image{
profilePicImage.image = img
}
if let img1 = image{
leftProfilePicImg.image = img1
}
if let img2 = image{
rightProfilePicImg.image = img2
}
}
You need
enum ImageChooser {
case profile,left,right
}
class EditProfileImagesVC: UIViewController {
private var imagePicker : EasyImagePicker?
#IBOutlet weak var profilePicImage: UIImageView!
#IBOutlet weak var leftProfilePicImg: UIImageView!
#IBOutlet weak var rightProfilePicImg: UIImageView!
var chooser:ImageChooser = .profile
override func viewDidLoad() {
super.viewDidLoad()
imagePicker = EasyImagePicker(presentationController: self, delegate: self)
}
#IBAction func profilePicBtn(_ sender: UIButton) {
chooser = .profile
imagePicker?.present(from: sender, mediaType: .images, onViewController: self)
}
#IBAction func leftProfileBtn(_ sender: UIButton) {
chooser = .left
imagePicker1?.present(from: sender, mediaType: .images, onViewController: self)
}
#IBAction func rightProfileBtn(_ sender: UIButton) {
chooser = .right
imagePicker2?.present(from: sender, mediaType: .images, onViewController: self)
}
}
extension EditProfileImagesVC : EasyImagePickerDelegate{
func didSelect(image: UIImage?, video: URL?, fileName: String?) {
if let img = image {
if chooser == .profile {
profilePicImage.image = img
}
else
if chooser == .left {
leftProfilePicImg.image = img
}
else
if chooser == .right {
rightProfilePicImg.image = img
}
}
}
}
Add picker reference to func didSelect(image: UIImage?, video: URL?, fileName: String?)
This way func didSelect(picker: EaseImagePicker, image: UIImage?, video: URL?, fileName: String?)
From picker call it with the reference to self
didSelect(picker: self, image: selectedImage, video: nil, fileName: nil)
func didSelect(picker: EaseImagePicker, image: UIImage?, video: URL?, fileName: String?) {
if let img = image{
switch picker {
case imagePicker:
profilePicImage.image = img
case imagePicker1:
leftProfilePicImg.image = img
case imagePicker2:
rightProfilePicImg.image = img
default:
break
}
}
}
Related
This question already has answers here:
Xcode 8 says "Do you want to add a stub?" How do I answer?
(3 answers)
Closed 4 years ago.
I added the ImageView Protocol. What can be done to remove the error
Do you want to add protocol stubs?
CardsViewController
import UIKit
protocol ImageViewProtocol{
func sendImageToViewController(theImage: UIImage)
}
class CardsViewController: UIViewController, UIImagePickerControllerDelegate, UINavigationControllerDelegate, ImageViewProtocol {
#IBOutlet weak var textField: UITextField!
#IBOutlet weak var nameTextField: UITextField!
#IBOutlet weak var locationTextField: UITextField!
#IBOutlet weak var imageView: UIImageView!
#IBAction func goToViewController2Action(_ sender: Any)
{
let viewcontroller2 = storyboard?.instantiateViewController(withIdentifier: "viewController2") as! ViewController2
viewcontroller2.delegate = self
self.navigationController?.pushViewController(viewcontroller2, animated: true)
}
func chooseImagePickerAction(source: UIImagePickerController.SourceType) {
if UIImagePickerController.isSourceTypeAvailable(source) {
let imagePicker = UIImagePickerController()
imagePicker.delegate = self
imagePicker.allowsEditing = true
imagePicker.sourceType = source
self.present(imagePicker, animated: true, completion: nil)
}
}
#IBAction func saveButtonPressed(_ sender: UIBarButtonItem) {
if nameTextField.text == "" || locationTextField.text == "" || textField.text == "" {
print("Not all fields are filled")
} else {
if let context = (UIApplication.shared.delegate as? AppDelegate)?.coreDataStack.persistentContainer.viewContext {
let card = Card(context: context)
card.name = nameTextField.text
card.location = locationTextField.text
card.number = textField.text
if let image = imageView.image {
card.image = image.pngData()
}
do {
try context.save()
print("Cохранение удалось!")
} catch let error as NSError {
print("Не удалось сохранить данные \(error), \(error.userInfo)")
}
}
performSegue(withIdentifier: "unwindSegueFromNewCard", sender: self)
}
}
func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [UIImagePickerController.InfoKey : Any]) {
imageView.image = info[UIImagePickerController.InfoKey.editedImage] as? UIImage
imageView.contentMode = .scaleAspectFill
imageView.clipsToBounds = true
dismiss(animated: true, completion: nil)
}
}
ViewController2
import UIKit
class ViewController2: UIViewController {
var filter : CIFilter!
var delegate: ImageViewProtocol!
#IBOutlet weak var select: UISegmentedControl!
#IBOutlet weak var textField: UITextField!
#IBOutlet weak var barcodeImageView: UIImageView!
override func viewDidLoad() {
super.viewDidLoad()
barcodeImageView.image = UIImage(named: "photo")
}
#IBAction func saveButtonAction(_ sender: Any) {
if textField.text == "" {
print("Not all fields are filled")
} else {
delegate.sendImageToViewController(theImage: barcodeImageView.image!)
self.navigationController?.popViewController(animated: true)
}
performSegue(withIdentifier: "unwindSegueFromViewController", sender: sender)
}
#IBAction func tappedEnter(_ sender: Any) {
if textField.text?.isEmpty ?? true {
return
} else {
if let texttxt = textField.text {
let data = texttxt.data(using: .ascii, allowLossyConversion: false)
if select.selectedSegmentIndex == 0
{
filter = CIFilter(name: "CICode128BarcodeGenerator")
} else {
filter = CIFilter(name: "CIQRCodeGenerator")
}
filter.setValue(data, forKey: "inputMessage")
let transform = CGAffineTransform(scaleX: 5, y: 5)
let image = UIImage(ciImage: filter.outputImage!.transformed(by: transform))
barcodeImageView.image = image
}
}
}
}
This error comes because you implemented protocol (ImageViewProtcol) but you haven't add required methods of your protocol (in your case sendImageToViewController(theImage: UIImage)). All methods of your protocol are required by default. If you want to change it, you can look here.
It's the same as when you're implementing UITableViewDataSource, you also need to add required methods like number of items etc.
To fix this, add this method to your CardsViewController:
func sendImageToViewController(theImage: UIImage) {
// do something with image
}
I am developing an App that will ask for 5 images, assign them to the proper UIImageViewer for preview purposes, and then I would like to hit upload and all 5 images go to a team drive. At this point all of it works except the code snippet I have is only able to upload images if they are in the App's Documents Directory. I would like to reference back to the 5 previously chosen images and upload them to a team drive but I do not know how to go about that.
Each button has been assigned a tag number, in which will equal their designated UIImageViewer. I am trying to reference the other previously chosen images but an error says in the 'UploadAction' button "Cannot convert value of type 'UIImage' to expected argument type 'String'". Here is my code, any help would be greatly appreciated!! (This is in Swift in Xcode, I could not find any examples using swift to upload pictures using a phone camera or photo gallery)
import UIKit
import GoogleSignIn
import GoogleAPIClientForREST
class ViewController: UIViewController, UIImagePickerControllerDelegate, UINavigationControllerDelegate, GIDSignInUIDelegate, UIPickerViewDelegate, UITextFieldDelegate{
// func numberOfComponents(in pickerView: UIPickerView) -> Int {
//
// }
// func pickerView(_ pickerView: UIPickerView, numberOfRowsInComponent component: Int) -> Int {
//
// }
#IBOutlet weak var imageView1: UIImageView!
#IBOutlet weak var imageView2: UIImageView!
#IBOutlet weak var imageView3: UIImageView!
#IBOutlet weak var imageView4: UIImageView!
#IBOutlet weak var imageView5: UIImageView!
#IBOutlet weak var resultsLabel: UILabel!
var imagePicker = UIImagePickerController()
var imagePicked = 0
var cameraPicker = UIImagePickerController()
var cameraPicked = 0
fileprivate let service = GTLRDriveService()
private var drive: ATGoogleDrive?
override func viewDidLoad() {
super.viewDidLoad()
cameraPicker.delegate = self
cameraPicker.sourceType = .camera
cameraPicker.allowsEditing = false; imagePicker.delegate = self
imagePicker.sourceType = .savedPhotosAlbum
imagePicker.allowsEditing = false;
GIDSignIn.sharedInstance().uiDelegate = self;
self.view.backgroundColor = UIColor.lightGray;
setupGoogleSignIn()
drive = ATGoogleDrive(service)
}
#IBAction func openCamera(_ sender: UIButton){
if UIImagePickerController.isSourceTypeAvailable(UIImagePickerController.SourceType.camera){
cameraPicked = sender.tag
present(cameraPicker, animated: true)
}
}
#IBAction func chooseImage1(_ sender: UIButton) {
if UIImagePickerController.isSourceTypeAvailable(UIImagePickerController.SourceType.savedPhotosAlbum){
imagePicked = sender.tag
present(imagePicker, animated: true)
}
}
func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [UIImagePickerController.InfoKey : Any]) {
let pickedImage = info[UIImagePickerController.InfoKey.originalImage] as? UIImage;
let cameraImage = info[UIImagePickerController.InfoKey.originalImage] as? UIImage;
if imagePicked == 1 {
imageView1.image = pickedImage
} else if imagePicked == 2 {
imageView2.image = pickedImage
} else if imagePicked == 3 {
imageView3.image = pickedImage
} else if imagePicked == 4 {
imageView4.image = pickedImage
} else if imagePicked == 5 {
imageView5.image = pickedImage
} else if cameraPicked == 6 {
imageView1.image = cameraImage
} else if cameraPicked == 7 {
imageView2.image = cameraImage
} else if cameraPicked == 8 {
imageView3.image = cameraImage
} else if cameraPicked == 9 {
imageView4.image = cameraImage
} else if cameraPicked == 10 {
imageView5.image = cameraImage
}
dismiss(animated: true)
}
func imagePickerControllerDidCancel(_ picker: UIImagePickerController) {
dismiss(animated: true)
}
private func setupGoogleSignIn() {
GIDSignIn.sharedInstance().delegate = self
GIDSignIn.sharedInstance().uiDelegate = self
GIDSignIn.sharedInstance().scopes = [kGTLRAuthScopeDriveFile]
GIDSignIn.sharedInstance().signInSilently()
}
// MARK: - Actions
**#IBAction func uploadAction(_ sender: Any) {
if let documentsDir = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask).last {
let uploadem = imageView1.image
drive?.uploadFile("agostini_tech_demo", filePath: uploadem, MIMEType: "image/png") { (fileID, error) in
print("Upload file ID: \(fileID); Error: \(error?.localizedDescription)")**
}
}
}
#IBAction func listAction(_ sender: Any) {
drive?.listFilesInFolder("agostini_tech_demo") { (files, error) in
guard let fileList = files else {
print("Error listing files: \(error?.localizedDescription)")
return
}
self.resultsLabel.text = fileList.files?.description
}
}
}
// MARK: - GIDSignInDelegate
extension ViewController: GIDSignInDelegate {
func sign(_ signIn: GIDSignIn!, didSignInFor user: GIDGoogleUser!, withError error: Error!) {
if let _ = error {
// service.authorizer = nil
} else {
// service.authorizer = user.authentication.fetcherAuthorizer()
}
}
}
I am currently trying to upload a photo URL and post caption onto my firebase database. The photos are currently being saved on firebase storage which is fine, however I would like for it to also appear on the firebase database.
I repeatedly find myself dealing with this error "Value of type 'StorageMetadata' has no member 'downloadURL'"
I understand that in firebase 5 to get the url from storage you need to call downloadURL on storage reference, not metadata. I have tried multiple ways and examples, but it all leads to errors.screenshot of error
#IBOutlet weak var photo: UIImageView!
#IBOutlet weak var captionTextView: UITextView!
#IBOutlet weak var removeButton: UIBarButtonItem!
#IBOutlet weak var shareButton: UIButton!
var selectedImage: UIImage?
override func viewDidLoad() {
super.viewDidLoad()
let tapGesture = UITapGestureRecognizer(target: self, action: #selector(self.handleSelectPhoto)); photo.addGestureRecognizer(tapGesture)
photo.isUserInteractionEnabled = true
}
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
handlePost()
}
func handlePost() {
if selectedImage != nil {
self.shareButton.isEnabled = true
self.removeButton.isEnabled = true
self.shareButton.backgroundColor = UIColor(red: 0, green: 0, blue: 0, alpha: 1)
}else{
self.shareButton.isEnabled = false
self.shareButton.backgroundColor = .lightGray
self.removeButton.isEnabled = false
}
}
override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
view.endEditing(true)
}
#objc func handleSelectPhoto() {
let pickerController = UIImagePickerController()
pickerController.delegate = self
present(pickerController, animated: true, completion: nil)
}
#IBAction func shareButton_TouchUpInside(_ sender: Any) {
view.endEditing(true)
let hud = JGProgressHUD(style: .dark)
hud.textLabel.text = "Loading"
hud.show(in: self.view)
hud.dismiss(afterDelay: 3.0)
if let profileImg = self.selectedImage, let imageData = UIImageJPEGRepresentation(profileImg, 0.1) {
let photoIdString = NSUUID().uuidString
let storageRef = Storage.storage().reference(forURL: ".......").child("posts").child(photoIdString)
storageRef.putData(imageData, metadata: nil, completion: { (metadata, error) in
if error != nil {
return
}
//let photoUrl = url?.absoluteString
let photoUrl = metadata?.downloadURL()?.absoluteString
self.sendDataToDatabase(photoUrl: photoUrl!)
}
)}
}
#IBAction func remove_TouchUpInside(_ sender: Any) {
clean()
handlePost()
}
func sendDataToDatabase(photoUrl: String) {
let ref = Database.database().reference()
let postsReference = ref.child("posts")
let newPostId = postsReference.childByAutoId().key
let newPostReference = postsReference.child(newPostId)
newPostReference.setValue(["photoUrl": photoUrl, "caption": captionTextView.text!], withCompletionBlock: {
(error, ref) in
if error != nil {
ProgressHUD.showError(error!.localizedDescription)
return
}
ProgressHUD.showSuccess("Success")
self.clean()
self.tabBarController?.selectedIndex = 0 // switches user back to selected tabbar 0 = first 1 = second etc.
})
}
func clean() {
self.captionTextView.text = ""
self.photo.image = UIImage(named:"placeholder-photo")
self.selectedImage = nil
}
}
extension CameraViewController: UIImagePickerControllerDelegate,
UINavigationControllerDelegate {
func imagePickerController(_ picker: UIImagePickerController,
didFinishPickingMediaWithInfo info: [String : Any]) {
print("did finish picking media")
if let image = info["UIImagePickerControllerOriginalImage"]
as? UIImage {
selectedImage = image
photo.image = image
}
// profileImage.image = infoPhoto
dismiss(animated: true, completion: nil)
}
}
import UIKit
import ProgressHUD
import FirebaseStorage
import FirebaseDatabase
class CameraViewController: UIViewController {
#IBOutlet weak var photo: UIImageView!
#IBOutlet weak var shareButton: UIButton!
#IBOutlet weak var captionTextView: UITextView!
#IBOutlet weak var removeButton: UIBarButtonItem!
var selectedImage: UIImage?
override func viewDidLoad() {
super.viewDidLoad()
let tapGesture = UITapGestureRecognizer(target: self, action: #selector(self.handleSelectPhoto))
photo.addGestureRecognizer(tapGesture)
photo.isUserInteractionEnabled = true
}
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
handlePost()
}
func handlePost(){
if selectedImage != nil {
self.shareButton.isEnabled = true
self.removeButton.isEnabled = true
self.shareButton.backgroundColor = UIColor(red: 0, green: 0, blue: 0, alpha: 1)
} else {
self.shareButton.isEnabled = false
self.removeButton.isEnabled = false
self.shareButton.backgroundColor = .lightGray
}
}
override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
view.endEditing(true)
}
#objc func handleSelectPhoto(){
let pickerController = UIImagePickerController()
pickerController.delegate = self
present(pickerController, animated: true, completion: nil)
}
// Share photos to the storage database
#IBAction func shareButton_TouchUpInside(_ sender: Any) {
view.endEditing(true)
ProgressHUD.show("Please wait...", interaction: false)
if let profileImg = self.selectedImage, let photoData = profileImg.jpegData(compressionQuality: 0.1) {
let photoIdString = NSUUID().uuidString
print(photoIdString)
let storageRef = Storage.storage().reference(forURL:Config.STORAGE_ROOT_REF).child("Posts").child(photoIdString)
storageRef.putData(photoData, metadata: nil, completion: { (metadata, error) in
if error != nil {
ProgressHUD.showError(error!.localizedDescription)
return
}
let photoUrl = metadata?.downloadURL()?.absoluteString
self.sendDataToDatabase(photoUrl: photoUrl!)
})
} else {
ProgressHUD.showError("Profile image can't be empty")
}
}
#IBAction func remove_touchUpInside(_ sender: Any) {
clean()
handlePost()
}
func sendDataToDatabase(photoUrl:String){
let ref = Database.database().reference()
let postsReference = ref.child("posts")
let newPostId = postsReference.childByAutoId().key
let newPostReference = postsReference.child(newPostId)
newPostReference.setValue(["photoUrl": photoUrl, "caption": captionTextView.text!], withCompletionBlock: {
(error, ref) in
if error != nil{
ProgressHUD.showError(error!.localizedDescription)
return
}
ProgressHUD.showSuccess("Success")
self.clean()
self.tabBarController?.selectedIndex = 0
})
}
func clean(){
self.captionTextView.text = ""
self.photo.image = UIImage(named: "placeholder-img")
self.shareButton = nil
}
}
extension CameraViewController : UIImagePickerControllerDelegate, UINavigationControllerDelegate {
func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [UIImagePickerController.InfoKey : Any]) {
print("did Finish picking media")
if let chosenImage = info[.originalImage] as? UIImage {
selectedImage = chosenImage
photo.image = chosenImage
}
dismiss(animated: true, completion: nil)
}
}
Use Above code, it will successfully upload the image and post that to the Firebase Database
I have a model - Movies.
and two controllers - first for search movie by title, second - for display result with poster, title and year.
Now i need to create some history search on my third controller
(searchHistoryController - TableView) where displayed all movies, and when i tapped on cell with movie's title show movie info.
How I can build it?
I tried create array in my model. And write resutl in it, but each time when i use search it rewrite array, not add new element.
Maybe use realm
Need some help:)
Movie.swift
import Foundation
import UIKit
import Alamofire
import AlamofireImage
protocol MovieDelegate {
func updateMovieInfo()
}
class Movie {
private let omdbUrl = "http://www.omdbapi.com/?"
var title: String?
var filmYear: String?
var poster: String?
var delegete: MovieDelegate!
var historyMovie = [Movie]()
func getMovieInfo(title: String, completion: #escaping ()->()){
let params = ["t": title]
Alamofire.request(omdbUrl, method: .get, parameters: params).validate(statusCode: 200..<300).validate(contentType: ["application/json"]).responseJSON { (response) in
switch response.result {
case .success(let JSON):
let response = JSON as! NSDictionary
let status = response["Response"] as! String
if status == "True" {
self.title = (response["Title"] as! String)
self.filmYear = (response["Year"] as! String)
self.poster = (response["Year"] as! String)
// self.delegete.updateMovieInfo()
completion()
} else {
self.title = (response["Error"] as! String)
completion()
}
case .failure(let error):
print (error)
}
}
}
}
SearchVC
import UIKit
class SearchViewController: UIViewController {
var movie = Movie()
#IBOutlet weak var activityIndicator: UIActivityIndicatorView!
#IBOutlet weak var searchTextField: UITextField!
#IBOutlet weak var searchButton: UIButton!
#IBAction func searchButtonTapped(_ sender: UIButton) {
activityIndicator.startAnimating()
DispatchQueue.main.async {
self.movie.getMovieInfo(title: self.searchTextField.text!, completion: {
self.activityIndicator.stopAnimating()
self.performSegue(withIdentifier: "movieInfo", sender: self)
})
}
}
override func viewDidLoad() {
super.viewDidLoad()
}
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
let secondVC = segue.destination as! DetailInfoViewController
secondVC.movieTitle = movie.title!
}
}
DetailVC
class DetailInfoViewController: UIViewController, MovieDelegate {
#IBAction func showHistory(_ sender: UIButton) {
performSegue(withIdentifier: "showHistory", sender: self)
}
#IBOutlet weak var posterImageView: UIImageView!
#IBOutlet weak var filmNameLabel: UILabel!
#IBOutlet weak var filmYearLabel: UILabel!
var movie = Movie()
var movieTitle = ""
override func viewDidLoad() {
super.viewDidLoad()
self.movie.getMovieInfo(title: movieTitle ) {
self.updateMovieInfo()
}
self.movie.delegete = self
}
func updateMovieInfo() {
getPoster(link: movie.poster)
filmNameLabel.text = movie.title
filmYearLabel.text = movie.filmYear
}
func getPoster(link: String?) {
if link != nil {
guard let url = URL(string: link!) else { return }
DispatchQueue.global().async {
if let data = try? Data(contentsOf: url) {
DispatchQueue.main.async {
self.posterImageView.image = UIImage(data: data)
}
}
} } else {
self.posterImageView.image = #imageLiteral(resourceName: "Image")
}
}
}
First of all, movieHistory should not be part of your Movie class, but part of your SearchViewController class.
Second of all, unless you want to persist your data, you don't need Realm for this.
Just save the movies in SearchViewController into an array once the search button has been tapped and send it to your other view controller in the segue. Like so
#IBAction func searchButtonTapped(_ sender: UIButton) {
activityIndicator.startAnimating()
DispatchQueue.main.async {
self.movie.getMovieInfo(title: self.searchTextField.text!, completion: {
self.activityIndicator.stopAnimating()
movieHistory.append(movie)
self.performSegue(withIdentifier: "movieInfo", sender: movieHistory)
})
}
}
Also, modify prepare(for segue:...) like this:
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
let secondVC = segue.destination as! DetailInfoViewController
secondVC.movieTitle = movie.title!
secondVC.movieHistory = movieHistory
}
In detailVC override prepare(for segue:...) as well and send movieHistory to searchHistoryController the same way it is done in the previous VC.
I cant figure out what's the problem here.
I have 6 images and when i click on them it popsup a image picker. If i choose a photo with a sequence, like 1,2,3,4,5,6... it works. But when i choose the first photo that's not the first one (array[0]), i get an error:
`$"Array index out of range"
Here is my code:
class SecondViewController: UIViewController,UIImagePickerControllerDelegate, UINavigationControllerDelegate {
var imagemEscolhida = -1
#IBOutlet var firstImageView: UIImageView!
#IBOutlet var secondImageView: UIImageView!
#IBOutlet var thirdImageView: UIImageView!
#IBOutlet var fourthImageView: UIImageView!
#IBOutlet var fifthImageView: UIImageView!
#IBOutlet var sixthImageView: UIImageView!
#IBAction func firstImageButton(sender: AnyObject) {
imagemEscolhida = 1
abreBibliotecaFotos(imagemEscolhida)
}
#IBAction func secondImageButton(sender: AnyObject) {
imagemEscolhida = 2
abreBibliotecaFotos(imagemEscolhida)
}
#IBAction func thirdImageButton(sender: AnyObject) {
imagemEscolhida = 3
abreBibliotecaFotos(imagemEscolhida)
}
#IBAction func fourthImageButton(sender: AnyObject) {
imagemEscolhida = 4
abreBibliotecaFotos(imagemEscolhida)
}
#IBAction func fifthImageButton(sender: AnyObject) {
imagemEscolhida = 5
abreBibliotecaFotos(imagemEscolhida)
}
#IBAction func sixthImageButton(sender: AnyObject) {
imagemEscolhida = 6
abreBibliotecaFotos(imagemEscolhida)
}
func abreBibliotecaFotos (img: Int )
{
imagePicker.allowsEditing = false
imagePicker.sourceType = .PhotoLibrary
presentViewController(imagePicker, animated: true, completion: nil)
}
let imagePicker = UIImagePickerController()
func imagePickerController(picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [NSObject : AnyObject]) {
if let pickedImage = info[UIImagePickerControllerOriginalImage] as? UIImage {
firstImageView.contentMode = .ScaleAspectFit
restaurante.imagem.insert(pickedImage, atIndex: imagemEscolhida-1)
switch imagemEscolhida
{
case 1:
firstImageView.image = restaurante.imagem[0]
case 2:
secondImageView.image = restaurante.imagem[1]
case 3:
thirdImageView.image = restaurante.imagem[2]
case 4:
fourthImageView.image = restaurante.imagem[3]
case 5:
fifthImageView.image = restaurante.imagem[4]
case 6:
sixthImageView.image = restaurante.imagem[5]
default:
println("Something else")
}
picker.dismissViewControllerAnimated(true, completion: nil)
}
dismissViewControllerAnimated(true, completion: nil)
}
func imagePickerControllerDidCancel(picker: UIImagePickerController) {
dismissViewControllerAnimated(true, completion: nil)
}
override func viewDidLoad() {
super.viewDidLoad()
imagePicker.delegate = self
}
}
You should initialize the array before you use it in the correct size. I would like to refer to my answer to a really similar question.
So initialize it from 0 to 5 at definition then your code should work.
It looks like the restaurante.imagem array is empty and your code crashes because you try to insert something at index which is higher than the maximum index of the array - which is 0.
The line to blame is:
restaurante.imagem.insert(pickedImage, atIndex: imagemEscolhida-1)