Search code examples
iosswiftuiimagepickercontroller

How can I allow a user to pick an image from their apple device?


I'm new to swift app development, so I am following apple's food tracker tutorial. Im trying to let the user set an image to one they have on their device. I copied their code exactly but its giving me an error saying

Cannot subscript a value of type '[String : AnyObject]' with an index of type 'UIImagePickerController.InfoKey'.

Here's my code, if you see the problem please let me know. p.s. Sorry for the code format, I don't know how to change that on stack.

 func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : AnyObject ]){
    // The info dictionary may contain multiple representations of the image. You want to use the original.
        guard let selectedImage = info[ UIImagePickerControllerOriginalImage ] as? UIImage else {
            fatalError("Expected a dictionary containing an image, but was provided the following: \(info)")
        }
        // Set photoImageView to display the selected image.
        photoImageView.image = selectedImage
        // Dismiss the picker.
        dismiss(animated: true, completion: nil)
 }

Solution

  • In Swift 4.2, the delegate method has been changed to:

    func imagePickerController(_ picker: UIImagePickerController, 
        didFinishPickingMediaWithInfo info: [UIImagePickerController.InfoKey : Any])
    

    And UIImagePickerControllerOriginalImage has been renamed to UIImagePickerController.InfoKey.originalImage.

    You should change your method signature and the name you use for the key. Your code should work fine.