Proper way to import screen recordings with SwiftUI PhotosPicker?

Hello,

I am building contact form that allows to attach screenshots and screen recordings. The PhotosPicker part is relatively straightforward but I am not sure how to properly import the selected items.

The binding is of type [PhotosPickerItem] which requires (at least for my current implementation) to first know if the item is image or video.

I have this not so pretty code to detect if the item is video:

let isVideo = item.supportedContentTypes.first(where: { $0.conforms(to: .video) }) != nil || item.supportedContentTypes.contains(.mpeg4Movie)

Which for screen recordings seems to work only because I ask about .mpeg4Movie and then I have this struct:

struct ScreenRecording: Transferable {
    let url: URL
    
    static var transferRepresentation: some TransferRepresentation {
        FileRepresentation(contentType: .mpeg4Movie) { video in
            SentTransferredFile(video.url)
        } importing: { received in
            let copy = URL.temporaryDirectory.appending(path: "\(UUID().uuidString).mp4")
            
            try FileManager.default.copyItem(at: received.file, to: copy)
            
            return Self.init(url: copy)
        }
    }
}

Notice here I have just the .mpeg4Movie content type, I couldn't get it to work with more generic ones like movie and I am afraid this implementation could soon break if the screen recordings change video format/codec.

And finally my logic to load the item:

if isVideo {
       if let movie = try? await item.loadTransferable(type: ScreenRecording.self) {
                    viewModel.addVideoAttachment(movie)
                }
       } else {
                if let data = try? await item.loadTransferable(type: Data.self) {
                    if let uiImage = UIImage(data: data) {
                        viewModel.addScreenshotAttachment(uiImage)
                    }
                }
            }

I would like to make this more "future proof" and less error prone - particularly the screen recordings part.

I don't even need the UIImage since I am saving the attachments as files, I just need to know if the attachment is screenshot or video and get its URL.

Thanks!

Proper way to import screen recordings with SwiftUI PhotosPicker?
 
 
Q