iosswiftphasset

How to get access to metadata for UIImage via PHAsset using Swift


I'm trying to get this working code that retrieves the UIImage via the selectedImage from the ImagePicker and saves it via the savePhoto method, to ALSO get me the metadata of the UImage:

Original Code:

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

    if let selectedImage = info[UIImagePickerController.InfoKey.originalImage] as? UIImage {

    //Successfully got the image, now upload it

        //Get a reference to the camera view controller and call the savePhoto method
        let cameraVC = self.selectedViewController as? CameraViewController

        if let cameraVC = cameraVC {
            cameraVC.savePhoto(image: selectedImage)
        }

//Dismiss the picker
picker.dismiss(animated: true, completion: nil)
}
}

This is what I tried but thisAsset always comes back nil so it skips over basically the entire method.

Code I tried:

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

var arrImageIdentifiers = String()


    if let thisAsset:PHAsset = info[UIImagePickerController.InfoKey.phAsset] as? PHAsset {
          arrImageIdentifiers.append(thisAsset.localIdentifier)

        //Get a reference to the camera view controller and call the savePhoto method
        let cameraVC = self.selectedViewController as? CameraViewController

        let manager = PHImageManager.default()

        manager.requestImage(for: thisAsset, targetSize: CGSize(width: 300.0, height: 300.0), contentMode: .aspectFit, options: nil, resultHandler: {(thisImage, _) in




        if let cameraVC = cameraVC {
            cameraVC.savePhoto(image: thisImage!)
        }
            })
        }
    self.dismiss(animated: true, completion: nil)
  }}

What's the easiest way to get the photo metadata (creationDate, location, etc) from the original code above?


Solution

  • The image you get from your first code does not include the metadata. Your second code is closer to being correct; you need to go back to the PHAsset and pick up the metadata from the photo library.

    This is what I tried but thisAsset always comes back nil

    Because you forgot to get user authorization for the photo library. Without that, you cannot access the PHAsset.