4

Apple's new iOS 14 PHPickerViewController delegate receives only an NSItemProvider. The 2020 WWDC video shows how to get from there to a UIImage:

    let prov = result.itemProvider
    prov.loadObject(ofClass: UIImage.self) { im, err in
        if let im = im as? UIImage {
            DispatchQueue.main.async {
                // display the image here

But what about if the user chose a live photo or a video? How do we get that?

matt
  • 515,959
  • 87
  • 875
  • 1,141

1 Answers1

7

Live photos are easy; do it exactly the same way. You can do that because PHLivePhoto is a class. So:

    let prov = result.itemProvider
    prov.loadObject(ofClass: PHLivePhoto.self) { livePhoto, err in
        if let photo = livePhoto as? PHLivePhoto {
            DispatchQueue.main.async {
                // display the live photo here

Videos are harder. The problem is that you do not want to be handed the data; it does you no good and is likely to be huge. You want the data saved to disk so that you can access the video URL, just like what UIImagePickerController used to do. You can in fact ask the item provider to save its data for you, but it wants to let go of that data when the completion handler returns. My solution is to access the URL in a .sync function:

    let prov = result.itemProvider
    prov.loadFileRepresentation(forTypeIdentifier: UTType.movie.identifier) { url, err in
        if let url = url {
            DispatchQueue.main.sync {
                // display the video here
matt
  • 515,959
  • 87
  • 875
  • 1,141
  • I am wondering why PHPickerViewController doesn't handle direct referencing of PHAsset to create video AVAsset that can be played or exported? When I select items and load selected PHAssets, it asks for permission for Photo library. But why is that needed when user already selected those items in the picker? – Deepak Sharma Oct 06 '20 at 09:44
  • @DeepakSharma Please ask it as a separate question. – matt Oct 06 '20 at 14:59
  • Already asked here https://stackoverflow.com/questions/64223430/phpickerviewcontroller-load-videos-via-phasset – Deepak Sharma Oct 06 '20 at 15:10