简体   繁体   English

从照片 iOS swift 中提取 GPS 数据

[英]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!我需要从 UIImagePickerController 选择的照片中获取 GPS 数据并提取要在 UIMapKit 中使用的照片的位置,我在 stackoverflow 和 Google 中尝试了一些示例代码,但没有一个对我有用! 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?我使用的照片包含纬度和经度数据,但它总是返回 nil 并出现这个致命错误:“在展开可选值时意外发现 nil”,我在模拟器上测试应用程序是否会导致任何问题? 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!但是当我通过拖放将照片复制到模拟器时,由于某种原因从照片中删除了 GPS 数据,我将照片存储到 Dropbox 并通过模拟器的 safari 下载它们! 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
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM