How to allow user to pick the image with Swift?

后端 未结 21 733
[愿得一人]
[愿得一人] 2020-12-02 06:01

I am writing my first iOS application (iPhone only) with Swift. The main application view should allow user to choose the image from the photo gallery.

I\'ve found

相关标签:
21条回答
  • 2020-12-02 06:25

    XCODE 10.1 / SWIFT 4.2 :

    1. Add required permissions (others mentioned)

    2. Add this class to your view:


        import UIKit
    
        import Photos
    
        import Foundation
    
    class UploadImageViewController: UIViewController, UIImagePickerControllerDelegate , UINavigationControllerDelegate {
    
            @IBOutlet weak var imgView: UIImageView!
    
            let imagePicker = UIImagePickerController()
    
            override func viewDidLoad() {
    
                super.viewDidLoad()
    
                checkPermission()
    
                imagePicker.delegate = self
                imagePicker.allowsEditing = false
                imagePicker.sourceType = .photoLibrary
            }
    
            @IBAction func btnSetProfileImageClickedCamera(_ sender: UIButton) {
            }
    
            @IBAction func btnSetProfileImageClickedFromGallery(_ sender: UIButton) {
                self.selectPhotoFromGallery()
            }
    
            func selectPhotoFromGallery() {
                self.present(imagePicker, animated: true, completion: nil)
            }
    
            func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [UIImagePickerController.InfoKey : Any]) {
    
                if let pickedImage = info[UIImagePickerController.InfoKey.originalImage] as? UIImage {
                        self.imgView.contentMode = .scaleAspectFit
                        self.imgView.image = pickedImage
                    }
    
                dismiss(animated: true, completion: nil)
            }
    
    
            func imagePickerControllerDidCancel(_ picker: UIImagePickerController){
                print("cancel is clicked")
            }
    
    
            func checkPermission() {
                let photoAuthorizationStatus = PHPhotoLibrary.authorizationStatus()
                switch photoAuthorizationStatus {
                case .authorized:
                    print("Access is granted by user")
                case .notDetermined:
                    PHPhotoLibrary.requestAuthorization({
                        (newStatus) in
                        print("status is \(newStatus)")
                        if newStatus ==  PHAuthorizationStatus.authorized {
                            /* do stuff here */
                            print("success")
                        }
                    })
                    print("It is not determined until now")
                case .restricted:
                    // same same
                    print("User do not have access to photo album.")
                case .denied:
                    // same same
                    print("User has denied the permission.")
                }
            }
        }
    
    0 讨论(0)
  • 2020-12-02 06:27

    I will give you best understandable coding for pick the image,refer this

    func tableView(tableView: UITableView!, didSelectRowAtIndexPath indexPath: NSIndexPath!) 
    {
         var alert:UIAlertController=UIAlertController(title: "Choose Image", message: nil, preferredStyle: UIAlertControllerStyle.ActionSheet)
         var cameraAction = UIAlertAction(title: "Camera", style: UIAlertActionStyle.Default)
         {
            UIAlertAction in
            self.openCamera()
         }
         var gallaryAction = UIAlertAction(title: "Gallary", style: UIAlertActionStyle.Default)
         {
            UIAlertAction in
            self.openGallary()
         }
         var cancelAction = UIAlertAction(title: "Cancel", style: UIAlertActionStyle.Cancel)
         {
            UIAlertAction in
         }
    
        // Add the actions
         picker?.delegate = self
         alert.addAction(cameraAction)
         alert.addAction(gallaryAction)
         alert.addAction(cancelAction)
         self.presentViewController(alert, animated: true, completion: nil)
    }
    func openCamera()
    {
        if(UIImagePickerController .isSourceTypeAvailable(UIImagePickerControllerSourceType.Camera))
        {
            picker!.sourceType = UIImagePickerControllerSourceType.Camera
            self .presentViewController(picker!, animated: true, completion: nil)
        }
        else
        {
            let alertWarning = UIAlertView(title:"Warning", message: "You don't have camera", delegate:nil, cancelButtonTitle:"OK", otherButtonTitles:"")
            alertWarning.show()
        }
    }
    func openGallary()
    {
        picker!.sourceType = UIImagePickerControllerSourceType.PhotoLibrary
        self.presentViewController(picker!, animated: true, completion: nil)
    }
    
    //PickerView Delegate Methods
    func imagePickerController(picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [NSObject : AnyObject])
    {
        picker .dismissViewControllerAnimated(true, completion: nil)
        imageView.image=info[UIImagePickerControllerOriginalImage] as? UIImage
    }
    func imagePickerControllerDidCancel(picker: UIImagePickerController)
    {
        println("picker cancel.")
    }
    

    Have a nice day:-)

    0 讨论(0)
  • 2020-12-02 06:28

    In Swift 5 you have to do this

    class ViewController: UIViewController, UIImagePickerControllerDelegate, UINavigationControllerDelegate {
    
        @IBOutlet var imageView: UIImageView!
        var imagePicker = UIImagePickerController()
    
        override func viewDidLoad() {
            super.viewDidLoad()
            // Do any additional setup after loading the view.
        }
    
        @IBAction func setPicture(_ sender: Any) {
            if UIImagePickerController.isSourceTypeAvailable(.photoLibrary){
                imagePicker.delegate = self
                imagePicker.sourceType = .photoLibrary
                imagePicker.allowsEditing = false
    
                present(imagePicker, animated: true, completion: nil)
            }
        }
    
        func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [UIImagePickerController.InfoKey : Any]) {
            picker.dismiss(animated: true, completion: nil)
            if let image = info[UIImagePickerController.InfoKey.originalImage] as? UIImage {
                imageView.image = image
            }
    
        }
    
    
    
    
    }
    
    0 讨论(0)
  • 2020-12-02 06:28

    For Swift 3.4.1, this code is working:

    implements                                                             
    class AddAdvertisementViewController : UINavigationControllerDelegate, UIImagePickerControllerDelegate, UIActionSheetDelegate  
    
    var imagePicker = UIImagePickerController()                                
    var file :UIImage!
    
     //action sheet tap on image
    
     func tapOnButton(){   
        let optionMenu = UIAlertController(title: nil, message: "Add Photo", preferredStyle: .actionSheet)
    
        let galleryAction = UIAlertAction(title: "Gallery", style: .default, handler:{
            (alert: UIAlertAction!) -> Void in
            self.addImageOnTapped()
        })
    
        let cameraAction = UIAlertAction(title: "Camera", style: .default, handler:{
            (alert: UIAlertAction!) -> Void in
            self.openCameraButton()
        })
    
        let cancleAction = UIAlertAction(title: "Cancel", style: .cancel, handler:{
            (alert: UIAlertAction!) -> Void in
            print("Cancel")
        })
    
        optionMenu.addAction(galleryAction)
        optionMenu.addAction(cameraAction)
        optionMenu.addAction(cancleAction)
        self.present(optionMenu, animated: true, completion: nil)
    }
    
    
    func openCameraButton(){
        if UIImagePickerController.isSourceTypeAvailable(UIImagePickerControllerSourceType.camera)
        {
            imagePicker = UIImagePickerController()
            imagePicker.delegate = self
            imagePicker.sourceType = UIImagePickerControllerSourceType.camera;
            imagePicker.allowsEditing = true
            self.present(imagePicker, animated: true, completion: nil)
        }
    }
    
    
    func addImageOnTapped(){
        if UIImagePickerController.isSourceTypeAvailable(UIImagePickerControllerSourceType.photoLibrary){
            imagePicker.delegate = self
            imagePicker.sourceType = UIImagePickerControllerSourceType.photoLibrary;
            imagePicker.allowsEditing = true
            self.present(imagePicker, animated: true, completion: nil)
        }
    }
    
    //picker pick image and store value imageview
    func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : Any]){
        if let image = info[UIImagePickerControllerOriginalImage] as? UIImage
        {
                file = image
                imgViewOne.image = image
            imagePicker.dismiss(animated: true, completion: nil);
        }
    }
    
    0 讨论(0)
  • 2020-12-02 06:28
    @IBAction func ImportImage(_ sender: Any)
    {
        let image = UIImagePickerController()
        image.delegate = self
    
        image.sourceType = UIImagePickerController.SourceType.photoLibrary
    
        image.allowsEditing = false
    
        self.present(image, animated: true)
        {
            //After it is complete
        }
    
    
    }
    
    func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [UIImagePickerController.InfoKey : Any]) {
        if let image = info[UIImagePickerController.InfoKey.originalImage] as? UIImage
        {
            myimage.image = image
        }
        else{
            //
        }
        self.dismiss(animated: true, completion: nil)
    
        do {
            try context.save()
        } catch {
            print("Could not save. \(error), \(error.localizedDescription)")
        }
    
    }
    

    Add UINavigationControllerDelegate, UIImagePickerControllerDelegate delegates in the class definition

    0 讨论(0)
  • 2020-12-02 06:29

    For Swift 4
    This code working for me!!

    import UIKit
    
    
    class ViewController: UIViewController, UINavigationControllerDelegate, UIImagePickerControllerDelegate {
    
        @IBOutlet var imageView: UIImageView!
        @IBOutlet var chooseBuuton: UIButton!
        var imagePicker = UIImagePickerController()
    
        override func viewDidLoad() {
            super.viewDidLoad()
            imagePicker.delegate = self
        }
        @IBAction func btnClicked() {
    
        if UIImagePickerController.isSourceTypeAvailable(.savedPhotosAlbum) 
        {
            print("Button capture")
            imagePicker.sourceType = .savedPhotosAlbum;
            imagePicker.allowsEditing = false
    
            self.present(imagePicker, animated: true, completion: nil)
            }
        }
    
      @objc func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : Any]) {
        let chosenImage = info[UIImagePickerControllerOriginalImage] as! UIImage
        imageView.image = chosenImage
    
        dismiss(animated: true, completion: nil)
        }
    }
    
    0 讨论(0)
提交回复
热议问题