Zach
Zach

Reputation: 4069

How to obtain photo data/metadata after being picked in PHPickerViewController?

In the app I work on, I am being tasked with a requirement to present the user their device photos using a PHPickerViewController.

Once selected, I need access to:

  1. The original image data
  2. The file name of the image
  3. The creation date of the image

This is simple to do with a PHAsset if I had full access to the user's photos - I could use the PHPickerViewController result value which includes photo identifiers to query PhotoKit for the PHAssets. However, there is no guarantee that I have full access. Additionally if the user has granted no access or limited access, and the limited selection does not include the photos being selected in the PHPickerViewController, I won't be able to query for them. (I tried this, and as expected the result of the query is nil, which makes sense).

The UIImage that I can obtain is only a proxy of the original image data (missing things like exif data, etc), so that is not sufficient for the user case my app has. Assuming there was an item provider for data, I'd still need to get information such as file name and creation date as well though.

So, is there a way to obtain this information?

Upvotes: 2

Views: 1953

Answers (1)

matt
matt

Reputation: 535138

The UIImage that I can obtain is only a proxy of the original image data (missing things like exif data, etc), so that is not sufficient for the user case my app has

Go back to the NSItemProvider and ask it for the data representation of the image. Now extract the metadata in the usual way.

// prov is the item provider
prov.loadDataRepresentation(forTypeIdentifier: UTType.image.identifier) { data, err in
    if let data = data {
        let src = CGImageSourceCreateWithData(data as CFData, nil)!
        let d = CGImageSourceCopyPropertiesAtIndex(src,0,nil) as! [AnyHashable:Any]
        print("metadata", d)
    }
}

Upvotes: 4

Related Questions