首页 > 解决方案 > How obtain GPS data from a photo

问题描述

I have been trying for a couple of days to find a way to obtain the GPS location from a photo inside the photo library. I'm using the UIImagePicker in order to obtain the photo but no one of the solutions posted on internet seems to work. I understood I should convert the UIImage to PHAsset but everywhere people are using a deprecated method called fetchAssets(withALAssetURLs: [URL], options: PHFetchOptions?). Is there any way to achieve this? Thank you very much

标签: iosswiftgpsuiimagephasset

解决方案


I hope this will help you:-

//step1:- import Photos

//step2:- when you presenting imagepicker controller

    if PHPhotoLibrary.authorizationStatus() == .authorized || PHPhotoLibrary.authorizationStatus() == .authorized{
        PHPhotoLibrary.requestAuthorization { [weak self](_) in
        // Present the UIImagePickerController
        self?.present(self!.imagePicker, animated: true, completion: nil)
    }
}

swift3.0 and Swift4.0

//step3:-
func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : Any]) {

    //obtaining saving path
    let fileManager = FileManager.default
    let documentsPath = fileManager.urls(for: .documentDirectory, in: .userDomainMask).first
    let imagePath = documentsPath?.appendingPathComponent("image.jpg")
    // extract image from the picker and save it
    if let pickedImage = info[UIImagePickerControllerOriginalImage] as? UIImage {
        let data = UIImageJPEGRepresentation(pickedImage, 0.75)
        data.write(toFile: localPath!, atomically: true)
    }

    let coordinate = (info[UIImagePickerControllerPHAsset] as? PHAsset)?.location?.coordinate
    print(coordinate?.latitude ?? "No latitude found")
    print(coordinate?.longitude ?? "No longitude found")
    self.dismiss(animated: true, completion: nil)
}

swift 4.2

func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [UIImagePickerController.InfoKey : Any]) {

    //obtaining saving path
    let fileManager = FileManager.default
    let documentsPath = fileManager.urls(for: .documentDirectory, in: .userDomainMask).first
    let imagePath = documentsPath?.appendingPathComponent("image.jpg")

    // extract image from the picker and save it
    if let pickedImage = info[UIImagePickerController.InfoKey.originalImage] as? UIImage {

        let imageData = pickedImage.jpegData(compressionQuality: 0.75)
        try! imageData?.write(to: imagePath!)
    }

    let coordinate = (info[UIImagePickerController.InfoKey.phAsset] as? PHAsset)?.location?.coordinate
    print(coordinate?.latitude ?? "No latitude found")
    print(coordinate?.longitude ?? "No longitude found")
    self.dismiss(animated: true, completion: nil)
}

enter image description here

Thanks


推荐阅读