Search code examples
swiftxcodeuiimagepickercontrollermailcore2

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


I'm work on a app which will be able to send mail without using IOS's client. I deciced to use the mailcore2 async api. For now I'm able to send an email but i'd like to add attachment to it and I'm actually trying to on the click of a button, open the gallery, select a picture and get its path. I'm trying this piece of code but an error appears at line 2 and 7 with my "

let imageURL

and

let image

":

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

Here is the code :

    func imagePickerController(picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [NSObject : AnyObject]) {
        let imageURL = info[UIImagePickerController.InfoKey.referenceURL] as NSURL
        let imageName = imageURL.path!.lastPathComponent
        let documentDirectory = NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true).first as! String
        let localPath = documentDirectory.stringByAppendingPathComponent(imageName)

        let image = info[UIImagePickerController.InfoKey.originalImage] as UIImage
        let data = UIImagePNGRepresentation(image)
        data.writeToFile(localPath, atomically: true)

        let imageData = NSData(contentsOfFile: localPath)!
        let photoURL = NSURL(fileURLWithPath: localPath)
        let imageWithData = UIImage(data: imageData)!

        picker.dismiss(animated: true, completion: nil)
    }

Solution

  • You’re using an older version of Swift, to get the image URL:

    let imageURL = info[UIImagePickerControllerReferenceURL] as NSURL
    

    I suggest that you upgrade to Swift 5.0 in the future