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
}
}
}
}
}