Leethal Leethal - 5 months ago 35
Swift Question

How can I get the CLLocation of a photo selected from UIImagePickerController in Swift?

UIImagePickerController selects an image from the user's photo library,

I'd just like to get the coordinates of the location of the selected photo, in Swift...

I have tried things like trying to get the photo's url....

func imagePickerController(picker: UIImagePickerController, didFinishPickingImage image: UIImage, editingInfo: [String : AnyObject]?) {
let imageURL = editingInfo![UIImagePickerControllerReferenceURL] as! NSURL
self.imageFromAsset(imageURL)
}


and passing that to...

func imageFromAsset(nsurl: NSURL) {
let asset = PHAsset.fetchAssetsWithALAssetURLs([nsurl], options: nil).firstObject as! PHAsset
var location = asset.location //then do something with this data
}


but getting the image url to begin with creates a fatal error.

Hope someone can help, thank you.

Error message:

fatal error: unexpectedly found nil while unwrapping an Optional value
(lldb)


This error appears to occur on this line:

let imageURL = editingInfo![UIImagePickerControllerReferenceURL] as! NSURL

Answer

Use func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : AnyObject]) instead of imagePickerController(picker: UIImagePickerController, didFinishPickingImage image: UIImage, editingInfo: [String : AnyObject]?)

Because it was deprecated in iOS 3.0

https://developer.apple.com/reference/uikit/uiimagepickercontrollerdelegate/1619152-imagepickercontroller