web-dev-qa-db-fra.com

Comment permettre à l'utilisateur de choisir l'image avec Swift?

J'écris ma première application iOS (iPhone uniquement) avec Swift. La vue principale de l'application devrait permettre à l'utilisateur de choisir l'image dans la galerie de photos. 

J'ai trouvé l'exemple de code suivant de ViewController.Swift:

class ViewController: UIImagePickerController, UINavigationControllerDelegate, UIImagePickerControllerDelegate  {

    override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view, typically from a nib.
    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }

    func tableView(tableView: UITableView!, didSelectRowAtIndexPath indexPath: NSIndexPath!) {

        var imagePickerController = UIImagePickerController()
        imagePickerController.delegate = self
        imagePickerController.sourceType = UIImagePickerControllerSourceType.SavedPhotosAlbum
        imagePickerController.allowsEditing = true
        self.presentViewController(imagePickerController, animated: true, completion: { imageP in

        })
    }


    func imagePickerController(picker: UIImagePickerController!, didFinishPickingImage image: UIImage!, editingInfo: NSDictionary!) {
        let selectedImage : UIImage = image
        println(selectedImage)
    }

}

et avoir la scène suivante View Controller -

View Controller
 - Top Layout Guide
 - Bottom Layout Guide
 - View
   - Image View
First Responder
Exit

Mais lorsque je lance l'application, seul un écran noir s'affiche. Qu'est-ce que je fais mal? Un autre exemple de code que j'ai trouvé est en Objective-C, ce qui ne m'aide pas.

51
LA_

Si vous voulez simplement laisser l’utilisateur choisir une image avec UIImagePickerController, utilisez ce code:

import UIKit


class 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

            self.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
    }
}
86
Dekel Maman

Pour Swift 3 

1- vous devez d’abord ajouter la clé suivante dans info.plist

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

2- Votre contrôleur View doit être conforme aux protocoles suivants UIImagePickerControllerDelegate, UINavigationControllerDelegate.

class ImagePickerViewController:  UIViewController,UIImagePickerControllerDelegate, UINavigationControllerDelegate {}

3-besoin de déclarer le UIImage vous serez utilisé pour lier l'image retournée/sélectionnée

  @IBOutlet weak var myImageView: UIImageView!
  @IBoutlet weak var upLoadImageBtn:UIImage!
  let imagePicker = UIImagePickerController()

4- Définissez le délégué pickerImage pour qu'il soit votre ViewController 

 imagePicker.delegate = self

5- Pour le bouton de téléchargement, vous devez aimer l'image suivante afin de déclencher l'action et d'afficher le sélecteur d'images.

@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- Votre contrôleur de vue doit implémenter les méthodes de délégué pour les délégués du sélecteur d'images. 

 // MARK: - ImagePicker Delegate

func 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)
}

Je vous souhaite une merveilleuse journée :)

29
Amr Angry

Sélecteur d'images de travail complet copié-collé pour Swift 4 basé sur @ user3182143

import Foundation
import UIKit


class 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()
    }

    func pickImage(_ viewController: UIViewController, _ callback: @escaping ((UIImage) -> ())) {
        pickImageCallback = callback;
        self.viewController = viewController;

        let cameraAction = UIAlertAction(title: "Camera", style: .default){
            UIAlertAction in
            self.openCamera()
        }
        let gallaryAction = UIAlertAction(title: "Gallary", 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(gallaryAction)
        alert.addAction(cancelAction)
        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 alertWarning = UIAlertView(title:"Warning", message: "You don't have camera", delegate:nil, cancelButtonTitle:"OK", otherButtonTitles:"")
            alertWarning.show()
        }
    }
    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)
    }

    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?) {
    }

}

Appelez-le depuis votre contrôleur de vue comme ceci:

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

N'oubliez pas non plus d'inclure les clés suivantes dans votre 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>
27
vir us

Je vais vous donner le meilleur codage compréhensible pour choisir l'image, reportez-vous à cette

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.")
}

Bonne journée:-)

12
user3182143
    @IBAction func chooseProfilePicBtnClicked(sender: AnyObject) {
    let alert:UIAlertController=UIAlertController(title: "Choose Image", message: nil, preferredStyle: UIAlertControllerStyle.ActionSheet)
    let cameraAction = UIAlertAction(title: "Camera", style: UIAlertActionStyle.Default)
        {
            UIAlertAction in
            self.openCamera()
    }
    let gallaryAction = UIAlertAction(title: "Gallary", style: UIAlertActionStyle.Default)
        {
            UIAlertAction in
            self.openGallary()
    }
    let 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 alert = UIAlertView()
        alert.title = "Warning"
        alert.message = "You don't have camera"
        alert.addButtonWithTitle("OK")
        alert.show()
    }
}
func openGallary(){
    picker.sourceType = UIImagePickerControllerSourceType.PhotoLibrary
    self.presentViewController(picker, animated: true, completion: nil)
}
//MARK:UIImagePickerControllerDelegate
func imagePickerController(picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : AnyObject]){
    picker .dismissViewControllerAnimated(true, completion: nil)
    imageViewRef.image=info[UIImagePickerControllerOriginalImage] as? UIImage
}
func imagePickerControllerDidCancel(picker: UIImagePickerController){
    print("picker cancel.")
}
6
Mannam Brahmam

XCODE 10.1/Swift 4.2:

  1. Ajouter les autorisations requises (autres mentionnées)

  2. Ajoutez cette classe à votre vue:


    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.")
            }
        }
    }
3
FRIDDAY

Je sais que cette question remonte à un an, mais voici un code assez simple (principalement de ce tutoriel ) qui fonctionne bien pour moi:

import UIKit

class ViewController: UIViewController, UIImagePickerControllerDelegate, UINavigationControllerDelegate {

@IBOutlet weak var imageView: UIImageView!

var imagePicker = UIImagePickerController()

override func viewDidLoad() {
    super.viewDidLoad()

    self.imagePicker.delegate = self
}

@IBAction func loadImageButtonTapped(sender: AnyObject) {
    print("hey!")
    self.imagePicker.allowsEditing = false
    self.imagePicker.sourceType = .SavedPhotosAlbum

    self.presentViewController(imagePicker, animated: true, completion: nil)
}

func imagePickerController(picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [NSObject : AnyObject]) {
    if let pickedImage = info[UIImagePickerControllerOriginalImage] as? UIImage {
        self.imageView.contentMode = .ScaleAspectFit
        self.imageView.image = pickedImage
    }

    dismissViewControllerAnimated(true, completion: nil)

}

func imagePickerControllerDidCancel(picker: UIImagePickerController) {
    self.imagePicker = UIImagePickerController()
    dismissViewControllerAnimated(true, completion: nil)
}
2
Rachel Harvey

Pour Swift 4
Ce code fonctionne pour moi !!

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)
    }
}
2

Faites ce genre de choses pour afficher des images de la bibliothèque de photos Swift coding:

var pkcrviewUI = UIImagePickerController()
        if UIImagePickerController .isSourceTypeAvailable(UIImagePickerControllerSourceType.PhotoLibrary)
        {
            pkcrviewUI.sourceType = UIImagePickerControllerSourceType.PhotoLibrary
            pkcrviewUI.allowsEditing = true
            pkcrviewUI.delegate = self
            [self .presentViewController(pkcrviewUI, animated: true , completion: nil)]
        }
2
NRV

Bien sûr, les réponses ci-dessus résolvent le problème principal.

J'ai rencontré un crash dans Swift 3.0 lors du lancement de l'album photo car Info.plist n'avait pas ces indicateurs:

  1. Confidentialité - Description d'utilisation de la photothèque -> NSPhotoLibraryUsageDescription

  2. Confidentialité - Description de l'utilisation de l'appareil photo -> NSCameraUsageDescription

[screenshot[1]

S'il vous plaît ajoutez-les si vous rencontrez un problème similaire.

Merci !

2

voici un moyen facile de le faire: 

mais vous devez d’abord ajouter (confidentialité - description de l’utilisation de la bibliothèque de photos) dans info.plist, et vous devez disposer d’un bouton et d’un UIImageView dans votre viewController.

puis créez une sortie de UIImageView (dans ce code, la sortie s'appelle myImage) et une action du bouton (j'ai appelé l'action d'importer dans mon code) 

import UIKit
class ViewController: UIViewController, UIImagePickerControllerDelegate, UINavigationControllerDelegate {

    override func viewDidLoad() {
        super.viewDidLoad()

    }
    @IBOutlet weak var myImage: UIImageView!
    @IBAction func importing(_ sender: Any) {
        let Picker = UIImagePickerController()
        Picker.delegate = self
        Picker.sourceType = .photoLibrary
        self.present(Picker, animated: true, completion: nil)
        Picker.allowsEditing = true
        Picker.mediaTypes = UIImagePickerController.availableMediaTypes(for: .photoLibrary)!
    }

     func imagePickerController(_ picker: UIImagePickerController,didFinishPickingMediaWithInfo info: [String : Any])
    {
        let chosenImage = info[UIImagePickerControllerOriginalImage] as! UIImage //1
        myImage.contentMode = .scaleAspectFit //2
        myImage.image = chosenImage //3
        dismiss(animated:true, completion: nil) //4
    }

}
1
alex's

Si vous ne voulez pas avoir un bouton séparé, voici une autre solution. Attaché un geste sur imageView lui-même, où sur le robinet de l'image une alerte va apparaître avec deux options. Vous aurez la possibilité de choisir entre galerie/photothèque ou d’annuler l’alerte.

import UIKit
import CoreData

class AddDetailsViewController: UIViewController, UITextFieldDelegate, UIImagePickerControllerDelegate, UINavigationControllerDelegate {

@IBOutlet weak var imageView: UIImageView!

var picker:UIImagePickerController? = UIImagePickerController()

@IBAction func saveButton(sender: AnyObject) {
    let managedContext = (UIApplication.sharedApplication().delegate as? AppDelegate)!.managedObjectContext

    let entity = NSEntityDescription.entityForName("Person", inManagedObjectContext: managedContext)

    let person = Person(entity: entity!, insertIntoManagedObjectContext: managedContext)

    person.image = UIImageJPEGRepresentation(imageView.image!, 1.0) //imageView.image

    do {
         try person.managedObjectContext?.save()
         //people.append(person)
       } catch let error as NSError {
         print("Could not save \(error)")
    }
}

override func viewDidLoad() {
    super.viewDidLoad()
    let tapGesture = UITapGestureRecognizer(target: self, action: #selector(AddDetailsViewController.tapGesture(_:)))
    imageView.addGestureRecognizer(tapGesture)
    imageView.userInteractionEnabled = true

    picker?.delegate = self
    // Do any additional setup after loading the view.
}

override func didReceiveMemoryWarning() {
    super.didReceiveMemoryWarning()
    // Dispose of any resources that can be recreated.
}

func tapGesture(gesture: UIGestureRecognizer) {
    let alert:UIAlertController = UIAlertController(title: "Profile Picture Options", message: nil, preferredStyle: UIAlertControllerStyle.ActionSheet)

    let gallaryAction = UIAlertAction(title: "Open Gallary", style: UIAlertActionStyle.Default) {
        UIAlertAction in self.openGallary()
    }

    let cancelAction = UIAlertAction(title: "Cancel", style: UIAlertActionStyle.Cancel) {
        UIAlertAction in self.cancel()
    }

    alert.addAction(gallaryAction)
    alert.addAction(cancelAction)

    self.presentViewController(alert, animated: true, completion: nil)

}


func openGallary() {
    picker!.allowsEditing = false
    picker!.sourceType = UIImagePickerControllerSourceType.PhotoLibrary
    presentViewController(picker!, animated: true, completion: nil)
}

func imagePickerController(picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : AnyObject]) {
    if let pickedImage = info[UIImagePickerControllerOriginalImage] as? UIImage {
        imageView.contentMode = .ScaleAspectFit
        imageView.image = pickedImage
    }

    dismissViewControllerAnimated(true, completion: nil)
}

func cancel(){
    print("Cancel Clicked")
}

}

En ajoutant plus à la question, implémenté la logique pour stocker des images dans CoreData. 

0
Ashutosh Jha

Répondez juste ici pour mentionner: info[UIImagePickerControllerEditedImage] est probablement celui que vous voulez utiliser dans la plupart des cas.

Autre que cela, les réponses ici sont complètes.

0
Lytic

Xcode 10, Swift 4.2

Vous trouverez ci-dessous une version légèrement optimisée de la mise en œuvre ..__ Ceci est dans Swift 4.2 et je l’ai aussi testé.

Vous pouvez voir le code complet de ViewController ici .. .. Veuillez noter que vous devez définir un IBOutlet (imageView) et IBAction (didTapOnChooseImageButton) définis et connectés au storyboard. J'espère que cela t'aides.

import UIKit

class ImagePickViewController: UIViewController,UIImagePickerControllerDelegate,UINavigationControllerDelegate {

var imagePicker = UIImagePickerController()
@IBOutlet weak var imageView: UIImageView!

override func viewDidLoad() {
    super.viewDidLoad()
    // Do any additional setup after loading the view.
}

@IBAction func didTapOnChooseImageButton(_ sender: Any) {
    let alert:UIAlertController=UIAlertController(title: "Choose Image", message: nil, preferredStyle: UIAlertController.Style.actionSheet)
    let cameraAction = UIAlertAction(title: "Camera", style: UIAlertAction.Style.default) {
        UIAlertAction in
        self.openCamera(UIImagePickerController.SourceType.camera)
    }
    let gallaryAction = UIAlertAction(title: "Gallary", style: UIAlertAction.Style.default) {
        UIAlertAction in
        self.openCamera(UIImagePickerController.SourceType.photoLibrary)
    }
    let cancelAction = UIAlertAction(title: "Cancel", style: UIAlertAction.Style.cancel) {
        UIAlertAction in
    }

    // Add the actions
    imagePicker.delegate = self as UIImagePickerControllerDelegate & UINavigationControllerDelegate
    alert.addAction(cameraAction)
    alert.addAction(gallaryAction)
    alert.addAction(cancelAction)
    self.present(alert, animated: true, completion: nil)
}

func openCamera(_ sourceType: UIImagePickerController.SourceType) {
    imagePicker.sourceType = sourceType
    self.present(imagePicker, animated: true, completion: nil)
}

//MARK:UIImagePickerControllerDelegate

func imagePickerController(_ picker: UIImagePickerController,
                                    didFinishPickingMediaWithInfo info: [UIImagePickerController.InfoKey : Any]) {
    imageView.image = info[UIImagePickerController.InfoKey.originalImage] as? UIImage
    imagePicker.dismiss(animated: true, completion: nil)
}

func imagePickerControllerDidCancel(_ picker: UIImagePickerController) {
    print("imagePickerController cancel")
}

}
0
Nish

Essayez celui-ci, rien de plus simple. Créer une image à l’aide de UIImagePickerControllerDelegate

    @objc func masterAction(_ sender: UIButton)
    {
        if UIImagePickerController.isSourceTypeAvailable(.savedPhotosAlbum){
            print("Button capture")

            imagePicker.delegate = self
            imagePicker.sourceType = .savedPhotosAlbum;
            imagePicker.allowsEditing = false

            self.present(imagePicker, animated: true, completion: nil)
        }

        print("hello i'm touch \(sender.tag)")
    }

    func imagePickerControllerDidCancel(_ picker:
        UIImagePickerController) {
        dismiss(animated: true, completion: nil)
    }

    func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : Any]) {
        if let chosenImage = info[UIImagePickerControllerOriginalImage] as? UIImage {
            print("Get Image \(chosenImage)")
            ImageList.insert(chosenImage, at: 0)
            ArrayList.insert("", at: 0)
            Collection_Vw.reloadData()
        } else{
            print("Something went wrong")
        }

        self.dismiss(animated: true, completion: nil)
    }
0
Super Developers

Si vous souhaitez sélectionner uniquement une image normale, vous pouvez utiliser le code ci-dessous, afin de vérifier que l'image sélectionnée n'est pas une image panoramique.

let picker = UIImagePickerController()

func photoFromLibrary() {

        self.picker.allowsEditing = true
        self.picker.sourceType = .photoLibrary
        //picker.mediaTypes = UIImagePickerController.availableMediaTypes(for: .photoLibrary)!

        self.present(self.picker, animated: true, completion: nil)

}

func shootPhoto() {

            if UIImagePickerController.isSourceTypeAvailable(.camera) {
                self.picker.allowsEditing = true
                self.picker.sourceType = UIImagePickerControllerSourceType.camera
                self.picker.cameraCaptureMode = .photo
                self.picker.modalPresentationStyle = .fullScreen
                self.present(self.picker,animated: true,completion: nil)
            }

}

//Image picker delegate
func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : Any]) {

    let str = "\(info["UIImagePickerControllerOriginalImage"]!)"

    let s = str.slice(from: "{", to: "}")

    if let arr = s?.components(separatedBy: ","){
        if arr.count >= 2 {
            if Int(arr[0])! > 11000 {
                picker.dismiss(animated:true, completion: nil)
                self.makeToast("Invalid Image!!!")
                return
            }
                     }
        }
    }

    if  let image = info[UIImagePickerControllerOriginalImage] as? UIImage{
        self.UserImageView.image = image
    }
    picker.dismiss(animated:true, completion: nil)
}


func imagePickerControllerDidCancel(_ picker: UIImagePickerController)
{
    picker.dismiss(animated: true, completion: nil)
}
0
Pankaj Jangid

cliquez sur le bouton et ouvrez Galerie d'images et définissez l'image dans imageview Swift 3.0

ajouter trois délégués.

var picker:UIImagePickerController?=UIImagePickerController()
@IBOutlet var imgPhoto: UIImageView!

   override func viewDidLoad() {
    super.viewDidLoad()
    picker?.delegate=self
   }

 @IBAction func btnAddPhotoClicked(_ sender: UIButton) {
    openGallary()
   }

func openGallary()
{
    picker!.allowsEditing = false
    picker!.sourceType = UIImagePickerControllerSourceType.photoLibrary
    present(picker!, animated: true, completion: nil)
}

//MARK:- ImagePicker Controller Delegate
//MARK:-

func imagePickerControllerDidCancel(_ picker: 
UIImagePickerController) {
    dismiss(animated: true, completion: nil)
}

func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : Any]) {
    if let chosenImage = info[UIImagePickerControllerOriginalImage] as? UIImage {
        imgPhoto.contentMode = .scaleToFill
        imgPhoto.image = chosenImage
    } else{
        print("Something went wrong")
    }

    self.dismiss(animated: true, completion: nil)
}
0
Maulik Patel