Kernel
Kernel

Reputation: 31

Choose photo from library in swift doesn't work

In my app I have a "addImgBtn" that should let the user to choose image from his photos. also I have "profileImg" that store some temporary image.

When I click the "addImg" button it shows me all photos, but when I click "Choose" it doesn't replace the temporary image with the chosen one, here my code:

class myClass: UIViewController, UINavigationControllerDelegate, UIImagePickerControllerDelegate {

@IBOutlet weak var profileImg: UIImageView!
@IBOutlet weak var addImgBtn: UIButton!

@IBAction func addImgBtn(_ sender: Any) {
        imagePicker.delegate = self
        imagePicker.sourceType = UIImagePickerControllerSourceType.photoLibrary
        imagePicker.allowsEditing = true
        self.present(imagePicker, animated: true, completion: nil)
}

func imagePickerController(picker: UIImagePickerController!, didFinishPickingImage image: UIImage!, editingInfo: NSDictionary!){
    self.dismiss(animated: true, completion: { () -> Void in

    })

    profileImg.image = image
 }
}

Upvotes: 0

Views: 201

Answers (1)

Unis Barakat
Unis Barakat

Reputation: 886

You are using the wrong imagePickerController method, change to the following:

 func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : Any]) {
    self.dismiss(animated: true, completion: { () -> Void in
        if let image = info[UIImagePickerControllerOriginalImage] as? UIImage {
            self.profileImg.image = image
        }
    })
}

This should work! As a general tip, command-click into UIImagePickerControllerDelegate or any delegate you are implementing in xcode and it will tell you all available methods,etc.

Upvotes: 1

Related Questions