Learn Courses My Dashboard

PH Image Picker for Videos

Hello community!
I want to enable the user to pick a video from their photo library, that is then displayed inside of my app.
Doing this with an image is fairly easy and there is a lot of information about it on the internet. With videos it’s different tough, I could not find much.

I have to change the code bellow, so that I can process a video instead of an UIImage. How can I do that, so that the @Binding var returns a video? The only thing I have changed yet, is the config.filter to .videos instead of .images. When I open the picker on a device, I can already select videos, but when I click on them the picker dismisses with this console message: [Picker] Showing picker unavailable UI (reason: still loading) with error: (null). I figure this happens, because this code can only return an image. Does anyone know how to do this with a video?

import PhotosUI
import SwiftUI

struct VideoPicker: UIViewControllerRepresentable {
    @Binding var image: UIImage?

    func makeUIViewController(context: Context) -> PHPickerViewController {
        var config = PHPickerConfiguration()
        config.filter = .videos
        let picker = PHPickerViewController(configuration: config)
        picker.delegate = context.coordinator
        return picker
    }

    func updateUIViewController(_ uiViewController: PHPickerViewController, context: Context) {

    }

    func makeCoordinator() -> Coordinator {
        Coordinator(self)
    }

    class Coordinator: NSObject, PHPickerViewControllerDelegate {
        let parent: VideoPicker

        init(_ parent: VideoPicker) {
            self.parent = parent
        }

        func picker(_ picker: PHPickerViewController, didFinishPicking results: [PHPickerResult]) {
            picker.dismiss(animated: true)

            guard let provider = results.first?.itemProvider else { return }

            if provider.canLoadObject(ofClass: UIImage.self) {
                provider.loadObject(ofClass: UIImage.self) { image, _ in
                    self.parent.image = image as? UIImage
                }
            }
        }
    }
}

Loading videos is a bit more complicated than loading photos, because you have to deal with file URLs and copying the video from a temporary location to some place you control.

Rather than work it out here, I’ll just point you to this tutorial at AppCoda

1 Like

As always a really helpful answer :D-thanks a lot!! For some reason using the File Manager to save media doesn’t work as described on the website (media disappears after closing the App) , so I gotta try it myself. Have I understood correctly, that the document directory is the best place to save user generated videos locally?