我需要通过UIImagePickerController从拾取的照片中获取GPS数据并提取要在UIMapKit中使用的照片的位置,我在stackoverflow和Google中尝试了一些示例代码,但它们都没有为我工作!我使用的照片包含纬度和经度数据但它总是返回nil这个致命的错误:“在解开一个可选值时意外发现nil”,我在模拟器上测试应用程序是否会导致任何问题?我考虑过各种各样的问题,我在某处做错了吗?这是代码
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)}
答案 0 :(得分:2)
我找到了解决方案,代码是正确的!但是当我通过拖放将照片复制到模拟器时由于某种原因从照片中删除GPS数据,我将照片存储到Dropbox并通过模拟器的safari下载它们! 参考Is it possible to access a photo's geotag metadata from within the simulator?
答案 1 :(得分:2)
这是更干净的方式。
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
}