Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

extract GPS data from photo iOS swift

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)}
like image 740
Samira Avatar asked Jan 29 '16 16:01

Samira


2 Answers

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?

like image 179
Samira Avatar answered Oct 07 '22 14:10

Samira


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
}
like image 40
Denis Kakačka Avatar answered Oct 07 '22 14:10

Denis Kakačka