I need to get GPS data from the picked photo by UIImagePickerController and extract the location of the photo to be used in UIMapKit, I tried some sample codes in stackoverflow and Google but none of them worked for me! the photo that I use contain latitude and longitude data but it always return nil with this fatal error: "unexpectedly found nil while unwrapping an Optional value", I test the app on emulator does it cause any problem? I considered all kinds of issues, am I doing wrong somewhere? here is the code
func imagePickerController(picker: UIImagePickerController!, didFinishPickingMediaWithInfo info: NSDictionary!) {
if picker.sourceType == UIImagePickerControllerSourceType.PhotoLibrary {
let url: AnyObject? = info[UIImagePickerControllerReferenceURL] as? NSURL
let library = ALAssetsLibrary()
library.assetForURL(url as NSURL, resultBlock: { (asset: ALAsset!) -> Void in
if asset != nil {
var assetRep: ALAssetRepresentation = asset.defaultRepresentation()
var metaData: NSDictionary = assetRep.metadata()
let location = metaData.objectForKey(ALAssetPropertyLocation) as CLLocation!
let lat = location.coordinate.latitude
let long = location.coordinate.longitude
}
}, failureBlock: {
(error: NSError!) in
NSLog("Error!")
}
)} dismissViewControllerAnimated(true, completion: nil)}
I found the solution,the code is correct! but when I copy a photo to the simulator via drag and drop the GPS data is removed from the photo for some reason, I store photos onto Dropbox and download them through safari of the simulator! by reference to Is it possible to access a photo's geotag metadata from within the simulator?
This is much cleaner way.
import Photos
func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [UIImagePickerController.InfoKey: Any]) {
guard let asset = info[.phAsset] as? PHAsset else { return }
// Do whatever
asset.location?.coordinate.latitude
asset.location?.coordinate.longitude
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With