How to allow user to pick the image with Swift? How to allow user to pick the image with Swift? ios ios

How to allow user to pick the image with Swift?


If you just want let the user choose image with UIImagePickerController use this code:

import UIKitclass ViewController: UIViewController, UINavigationControllerDelegate, UIImagePickerControllerDelegate {    @IBOutlet var imageView: UIImageView!    @IBOutlet var chooseBuuton: UIButton!    var imagePicker = UIImagePickerController()    @IBAction func btnClicked() {        if UIImagePickerController.isSourceTypeAvailable(.savedPhotosAlbum){            print("Button capture")            imagePicker.delegate = self            imagePicker.sourceType = .savedPhotosAlbum            imagePicker.allowsEditing = false            present(imagePicker, animated: true, completion: nil)        }    }    func imagePickerController(picker: UIImagePickerController!, didFinishPickingImage image: UIImage!, editingInfo: NSDictionary!){        self.dismiss(animated: true, completion: { () -> Void in        })        imageView.image = image    }}


Complete copy-paste working image picker for swift 4 based on @user3182143 answer:

import Foundationimport UIKitclass ImagePickerManager: NSObject, UIImagePickerControllerDelegate, UINavigationControllerDelegate {    var picker = UIImagePickerController();    var alert = UIAlertController(title: "Choose Image", message: nil, preferredStyle: .actionSheet)    var viewController: UIViewController?    var pickImageCallback : ((UIImage) -> ())?;        override init(){        super.init()        let cameraAction = UIAlertAction(title: "Camera", style: .default){            UIAlertAction in            self.openCamera()        }        let galleryAction = UIAlertAction(title: "Gallery", style: .default){            UIAlertAction in            self.openGallery()        }        let cancelAction = UIAlertAction(title: "Cancel", style: .cancel){            UIAlertAction in        }        // Add the actions        picker.delegate = self        alert.addAction(cameraAction)        alert.addAction(galleryAction)        alert.addAction(cancelAction)    }    func pickImage(_ viewController: UIViewController, _ callback: @escaping ((UIImage) -> ())) {        pickImageCallback = callback;        self.viewController = viewController;        alert.popoverPresentationController?.sourceView = self.viewController!.view        viewController.present(alert, animated: true, completion: nil)    }    func openCamera(){        alert.dismiss(animated: true, completion: nil)        if(UIImagePickerController .isSourceTypeAvailable(.camera)){            picker.sourceType = .camera            self.viewController!.present(picker, animated: true, completion: nil)        } else {            let alertController: UIAlertController = {                let controller = UIAlertController(title: "Warning", message: "You don't have camera", preferredStyle: .alert)                let action = UIAlertAction(title: "OK", style: .default)                controller.addAction(action)                return controller            }()            viewController?.present(alertController, animated: true)        }    }    func openGallery(){        alert.dismiss(animated: true, completion: nil)        picker.sourceType = .photoLibrary        self.viewController!.present(picker, animated: true, completion: nil)    }        func imagePickerControllerDidCancel(_ picker: UIImagePickerController) {        picker.dismiss(animated: true, completion: nil)    }    //for swift below 4.2    //func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : Any]) {    //    picker.dismiss(animated: true, completion: nil)    //    let image = info[UIImagePickerControllerOriginalImage] as! UIImage    //    pickImageCallback?(image)    //}        // For Swift 4.2+    func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [UIImagePickerController.InfoKey : Any]) {        picker.dismiss(animated: true, completion: nil)        guard let image = info[.originalImage] as? UIImage else {            fatalError("Expected a dictionary containing an image, but was provided the following: \(info)")        }        pickImageCallback?(image)    }    @objc func imagePickerController(_ picker: UIImagePickerController, pickedImage: UIImage?) {    }}

Call it from your viewcontroller like this:

    ImagePickerManager().pickImage(self){ image in        //here is the image    }

Also don't forget to include the following keys in your info.plist:

<key>NSCameraUsageDescription</key><string>This app requires access to the camera.</string><key>NSPhotoLibraryUsageDescription</key><string>This app requires access to the photo library.</string>


For Swift 3:

  1. First, you need to add the following key in info.plist:

        <key>NSPhotoLibraryUsageDescription</key><string>This app requires access to the photo library.</string>
  2. Your View controller needs to conform to the following protocols:UIImagePickerControllerDelegate, UINavigationControllerDelegate:

    class ImagePickerViewController:  UIViewController,UIImagePickerControllerDelegate, UINavigationControllerDelegate {}
  3. You need to declare the UIImage you will be useing to bind the returned/selected image:

    @IBOutlet weak var myImageView: UIImageView!@IBoutlet weak var upLoadImageBtn:UIImage!let imagePicker = UIImagePickerController()
  4. Set the pickerImage delegate to be your ViewController:

    imagePicker.delegate = self
  5. For the upload button, you will need to link to the following image in order to fire the action and display the image picker:

    @IBAction func upLoadImageBtnPressed(_ sender: AnyObject) {    imagePicker.allowsEditing = false    imagePicker.sourceType = .photoLibrary    /*    The sourceType property wants a value of the enum named        UIImagePickerControllerSourceType, which gives 3 options:    UIImagePickerControllerSourceType.PhotoLibrary    UIImagePickerControllerSourceType.Camera    UIImagePickerControllerSourceType.SavedPhotosAlbum    */    present(imagePicker, animated: true, completion: nil)}
  6. Your View controller needs to implement the delegate methods for the image picker delegates:

    // MARK: - ImagePicker Delegatefunc imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : Any]) {    if let pickedImage = info[UIImagePickerControllerOriginalImage] as? UIImage {        myImageView.contentMode = .scaleAspectFit        myImageView.image = pickedImage    }    /*    Swift Dictionary named “info”.      We have to unpack it from there with a key asking for what media information we want.    We just want the image, so that is what we ask for.  For reference, the available options are:    UIImagePickerControllerMediaType    UIImagePickerControllerOriginalImage    UIImagePickerControllerEditedImage    UIImagePickerControllerCropRect    UIImagePickerControllerMediaURL    UIImagePickerControllerReferenceURL    UIImagePickerControllerMediaMetadata    */    dismiss(animated: true, completion: nil)}func imagePickerControllerDidCancel(_ picker: UIImagePickerController) {    dismiss(animated: true, completion:nil)}