iOS 17 swift get GPS Location from Image


I was fetching the Image from photo library and fetch the GPS Location data, But It’s not working

This needs to work on iOS 17 as well, So I used PHPicker kCGImagePropertyGPSDictionary is always returning nil.

In photos app location data is available, but in code, it’s returning nil.
enter image description here

The code we tried.

import UIKit
import CoreLocation
import MobileCoreServices
import PhotosUI
class ViewController: UIViewController, UIImagePickerControllerDelegate, UINavigationControllerDelegate {
    @IBOutlet weak var selectedImageView:UIImageView!
    @IBAction func selectTheImage() {
        self.pickImageFromLibrary_PH()
    }
    func pickImageFromLibrary_PH() {
        var configuration = PHPickerConfiguration()
        configuration.filter = .images
        let picker = PHPickerViewController(configuration: configuration)
        picker.delegate = self
        present(picker, animated: true, completion: nil)
    }
    func picker(_ picker: PHPickerViewController, didFinishPicking results: [PHPickerResult]) {
        if let itemProvider = results.first?.itemProvider, itemProvider.canLoadObject(ofClass: UIImage.self) {
            itemProvider.loadObject(ofClass: UIImage.self) { (image, error) in
                if let image = image as? UIImage {
                    self.fetchLocation(for: image)
                }
            }
        }
        picker.dismiss(animated: true, completion: nil)
    }
    func fetchLocation(for image: UIImage) {
        let locationManager = CLLocationManager()
        guard let imageData = image.jpegData(compressionQuality: 1.0) else {
            print("Unable to fetch image data.")
            return
        }
        guard let source = CGImageSourceCreateWithData(imageData as CFData, nil) else {
            print("Unable to create image source.")
            return
        }
        guard let properties = CGImageSourceCopyPropertiesAtIndex(source, 0, nil) as? [String: Any] else {
            print("Unable to fetch image properties.")
            return
        }
        if let gpsInfo = properties[kCGImagePropertyGPSDictionary as String] as? [String: Any],
           let latitude = gpsInfo[kCGImagePropertyGPSLatitude as String] as? CLLocationDegrees,
           let longitude = gpsInfo[kCGImagePropertyGPSLongitude as String] as? CLLocationDegrees {
            let location = CLLocation(latitude: latitude, longitude: longitude)
            print("Image was taken at \(location.coordinate.latitude), \(location.coordinate.longitude)")
        } else {
            print("PHPicker- Location information not found in the image.")
        }
    }
}

Latest articles

spot_imgspot_img

Related articles

Leave a reply

Please enter your comment!
Please enter your name here

spot_imgspot_img