Home > Back-end >  Swift: How to handle video and photo results from a PHPicker?
Swift: How to handle video and photo results from a PHPicker?

Time:03-07

I need the ability for a user to select multiple photos and videos from there photo library. (Using PHPicker) I already know how to get images with this:

func picker(_ picker: PHPickerViewController, didFinishPicking results: [PHPickerResult]) {
    var contentsData: [Data] = []
    for result in results {
        if result.itemProvider.canLoadObject(ofClass: UIImage.self) {
            result.itemProvider.loadObject(ofClass: UIImage.self) { selectedData, error in
                if let error = error {
                    print("PICKER ERROR: \(error)")
                } else {
                    if let selectedImage = selectedData as? UIImage {
                        if let selectedImageData = selectedImage.jpegData(compressionQuality: 0.5) {
                            contentsData.append(selectedImageData)
                            if contentsData.count == results.count {
                                self.parent.completion(contentsData)
                            }
                        }
                    }
                }
            }
        }
    }
    self.parent.presentationMode.wrappedValue.dismiss()
}

I would assume that what I would need to do is check what data type each result from PHPickerResult is and then load each object accordingly. The problem is that a video file could be .mov, .mp4, etc. How can I identify a PHPickerResult as a video and handle it accordingly?

CodePudding user response:

Just ask whether the item provider has an item of type UTType.movie.identifier. If so, go ahead and load it by calling loadFileRepresentation(forTypeIdentifier: UTType.movie.identifier).

Actual code:

    if prov.hasItemConformingToTypeIdentifier(UTType.movie.identifier) {
        self.dealWithVideo(result)
    } else if prov.canLoadObject(ofClass: PHLivePhoto.self) {
        self.dealWithLivePhoto(result)
    } else if prov.canLoadObject(ofClass: UIImage.self) {
        self.dealWithImage(result)
    }
  • Related