Search code examples
swiftuiimageviewuiimagepickercontroller

Show image in imageview from gallery in swift


I am new in IOS and i want to show image in imageView which is picked from gallery.And i have also added the photo description in info.plist.But image is not showing in imageView.Here is my code:

import UIKit

class ViewController: UIViewController, UIImagePickerControllerDelegate,UINavigationControllerDelegate {
    @IBOutlet weak var img: UIImageView!
    @IBOutlet weak var imageView: UIImageView!
    @IBOutlet var chooseBuuton: UIButton!

    override func viewDidLoad() {
        super.viewDidLoad()

    }

    @IBAction func btnClicked() {
        let imagePicker = UIImagePickerController()
        imagePicker.delegate = self
        imagePicker.sourceType = UIImagePickerControllerSourceType.photoLibrary
        imagePicker.allowsEditing = false
        self.present(imagePicker, animated: true, completion: nil)
    }
    private func imagePickerController(picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : AnyObject]) {
        if let pickedImage = info[UIImagePickerControllerOriginalImage] as? UIImage {
            //imageView.contentMode = .scaleAspectFit
            img.image = pickedImage
        }
        self.dismiss(animated: true, completion: nil)
    }
}

Solution

  • Assuming that you are using Swift 3.x:

    You should implement imagePickerController(_:didFinishPickingMediaWithInfo:) as follows:

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

    And it should be good to go. What are the differences? well:

    1- Remove private.

    2- The signature of the method is not the same, as mentioned in the documentation, info should be of type [String : Any] not [String : AnyObject].