Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Have a reference to an image only having its NSURL. How to get a GPS metadata from it? Of course, I can load a UIImage from NSURL, but then what?

Majority of answers I've found here is regarding UIImagePicker, and using ALAssets then, but I have no such option.

like image 973
rshev Avatar asked Oct 27 '25 02:10

rshev


2 Answers

Answering my own question. The memory-effective and fast way to get a GPS metadata is

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]
}

The second option is

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

it looks nicer in Swift but uses more memory (tested via Profiler).

like image 113
rshev Avatar answered Oct 28 '25 18:10

rshev


Updated version for Swift 3:

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
    }
}
like image 29
Maury Markowitz Avatar answered Oct 28 '25 19:10

Maury Markowitz



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!