2

I'm trying to figure out how to load videos with PHPicker. I know how to do it with Images but I can't seem to figure out how to do it with videos. This code works only with some videos and not with others.

Here's my code

struct MediaPicker: UIViewControllerRepresentable {
@Binding var video: URL?
    
typealias UIViewControllerType = PHPickerViewController

class Coordinator: NSObject, PHPickerViewControllerDelegate {
    
    var parent: MediaPicker
    
    init(_ parent: MediaPicker) {
        self.parent = parent
    }
    
    func picker(_ picker: PHPickerViewController, didFinishPicking results: [PHPickerResult]) {
                    
        if results.isEmpty {
            picker.dismiss(animated: true)
            return
        }
        let provider = results.first!.itemProvider
        
        if provider.hasItemConformingToTypeIdentifier(UTType.movie.identifier) {
            provider.loadItem(forTypeIdentifier: UTType.movie.identifier) { url, err in
                if err != nil {return}
                if let url = url {
                    DispatchQueue.main.sync {
                        self.parent.video = url as! URL?
                        picker.dismiss(animated: true)
                    }
                }
            }
        }
    }
}

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

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

func makeCoordinator() -> Coordinator {
    return MediaPicker.Coordinator(self)
}
}

AVPlayer

blueskies
  • 43
  • 2
  • 7
  • 1
    I think the reason why only some are working is because it depends what type of video file each video is. (.mp4, .mov, etc.) That being said I dont know what to do with that info. I am in the same position as you. Any solutions? – Trevor Mar 06 '22 at 23:28
  • See https://stackoverflow.com/questions/71374994/swift-how-to-handle-video-and-photo-results-from-a-phpicker for solution – Trevor Mar 07 '22 at 01:44

0 Answers0