Jmuru Jmuru - 7 days ago 5
Swift Question

UIImageView not updating with new image after picture taken or picture chosen from photo library

I'm trying to populate an image within a UIImageView after I either take a picture or choose a picture from my photo library.

here is the code handling the camera and photo library activations:

@IBAction func activateCmera(_ sender: Any) {
if (UIImagePickerController.isSourceTypeAvailable(.camera)) {
let imagePicker = UIImagePickerController()
imagePicker.delegate = self
imagePicker.sourceType = .camera
imagePicker.allowsEditing = false
self.present(imagePicker, animated: true, completion: nil)
}
}


@IBAction func activatePhotoLib(_ sender: Any) {
if (UIImagePickerController.isSourceTypeAvailable(.photoLibrary)) {
let imagePicker = UIImagePickerController()
imagePicker.delegate = self
imagePicker.sourceType = .photoLibrary
imagePicker.allowsEditing = false
self.present(imagePicker, animated: true, completion: nil)
}
}


Here is the code that populates the image within the UIImageView:

@IBOutlet weak var imageView: UIImageView!

func imagePickerController(picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : AnyObject]) {
let image = info[UIImagePickerControllerOriginalImage] as! UIImage
self.imageView.contentMode = .scaleAspectFit
self.imageView.image = image
self.dismiss(animated: true, completion: nil);
}


currently after I take a picture with my camera or choose an image from my photo library, I'm redirected to the initial view of the app without UIImageView space updated with the photo.

Any help is appreciated thanks!

Joe Joe
Answer

In Swift 3 you need permission to access photoLibrary by adding below keys to your plist and you need to use the proper delegate method.

enter image description here

Add UIImagePickerControllerDelegate& UINavigationControllerDelegate to your classand set imagePicker delegate to viewDidLoad & Try below code.

    let imagePicker = UIImagePickerController()

    @IBAction func activatePhotoLib(_ sender: UIButton) { 
    if UIImagePickerController.isSourceTypeAvailable(UIImagePickerControllerSourceType.photoLibrary) {
        imagePicker.delegate = self
        imagePicker.sourceType = UIImagePickerControllerSourceType.photoLibrary;
        imagePicker.allowsEditing = false
        self.present(imagePicker, animated: true, completion: nil)
       } 
     }

    func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : Any]) {
    if let image = info[UIImagePickerControllerOriginalImage] as? UIImage {
        imageView.image = image
     }
    picker.dismiss(animated: true, completion: nil);
    }

Output: updated

enter image description here

Comments