iOS Swift。如何仅从 UIImage (NSURL) 获取 GPS 元数据?

iOS Swift. How to get a GPS metadata from just a UIImage (NSURL)?

引用一张只有 NSURL 的图片。 如何从中获取 GPS 元数据? 当然,我可以从 NSURL 加载一个 UIImage,但是然后呢?

我在这里找到的大部分答案都是关于 UIImagePicker,然后使用 ALAssets,但我没有这样的选择。

回答我自己的问题。获取 GPS 元数据的内存有效且快速的方法是

let options = [kCGImageSourceShouldCache as String: kCFBooleanFalse]
if let data = NSData(contentsOfURL: url), imgSrc = CGImageSourceCreateWithData(data, options) {
    let metadata = CGImageSourceCopyPropertiesAtIndex(imgSrc, 0, options) as Dictionary
    let gpsData = metadata[kCGImagePropertyGPSDictionary] as? [String : AnyObject]
}

第二个选项是

if let img = CIImage(contentsOfURL: url), metadata = img.properties(), 
gpsData = metadata[kCGImagePropertyGPSDictionary] as? [String : AnyObject] { … }

它在 Swift 中看起来更好,但使用更多内存(通过 Profiler 测试)。

Swift3 的更新版本:

let options = [kCGImageSourceShouldCache as String: kCFBooleanFalse]
if let data = NSData(contentsOfURL: url), let imgSrc = CGImageSourceCreateWithData(data, options as CFDictionary) {
    let metadata = CGImageSourceCopyPropertiesAtIndex(imgSrc, 0, options as CFDictionary) as? [String : AnyObject]
    if let gpsData = metadata?[kCGImagePropertyGPSDictionary as String] {
        //do interesting stuff here
    }
}