Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to fetch live photo or video from PHPickerViewController delegate

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?

like image 490
matt Avatar asked Oct 15 '25 17:10

matt


1 Answers

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
like image 115
matt Avatar answered Oct 18 '25 10:10

matt



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!