Save photo with geolocation data to photo library Swift 3

狂风中的少年 提交于 2019-12-04 08:54:07

In iOS 8 Apple introduced Photo Library.

Here is the example to create and update PHAsset with location:

func addAsset(image: UIImage, location: CLLocation? = nil) {
    PHPhotoLibrary.shared().performChanges({
        // Request creating an asset from the image.
        let creationRequest = PHAssetChangeRequest.creationRequestForAsset(from: image)
        // Set metadata location
        if let location = location {
            creationRequest.location = location
        }
    }, completionHandler: { success, error in
        if !success { NSLog("error creating asset: \(error)") }
    })
}

Make sure you authorized to access photos before saving with

PHPhotoLibrary.requestAuthorization(_:)

Metadata can be read with:

info[UIImagePickerControllerMediaMetadata]

I am not able to verify that metadata stores location, in my test NOT even with location service allowed. In that case use could get real location by yourself using CoreLocation.

Well I guess you need to access the location of the user first before you call func addAsset(image: UIImage, location: CLLocation? = nil) {...}

so somewhere in the func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : Any]) {....}

I am calling:

 let locationManager = CLLocationManager()

        if CLLocationManager.locationServicesEnabled() {
            locationManager.delegate = self
            locationManager.desiredAccuracy = kCLLocationAccuracyNearestTenMeters
            locationManager.startUpdatingLocation()

        }
        else{
            //Location service disabled"
        }
        //and then call....

        addAsset(image: pickedImage, location: locationManager.location)

once i finish with the:

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

i stop updating the location:

 locationManager.stopUpdatingLocation()

This works for me

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!