Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

iOS SwiftUI - pick image or video from gallery using PhotosPicker

Tags:

ios

swift

swiftui

I'm trying to use the new PhotosPicker:

PhotosPicker(
    selection: $selectedItem,
    matching: .videos,
    photoLibrary: .shared()) {
        Text("Select a photo")
    }
    .onChange(of: selectedItem) { newItem in
        Task {
            if let data = try? await newItem?.loadTransferable(type: Data.self) {
                selectedImageData = data
            }
        }
    }

how can I set to pick either image or video instead of only one of those?

I tried:

matching: [.images, .videos],

and get:

Cannot convert value of type '[Any]' to expected argument type 'PHPickerFilter?'
like image 395
Coddo Avatar asked Sep 02 '25 09:09

Coddo


1 Answers

Solution

Noticing that the matching parameter is of type PHPickerFilter, you can use the .any(of:) static function to combine filters. For example:

PhotosPicker("Pick Photo",
             selection: $item,
             matching: .any(of: [.images, .videos])) // <- combine filters

or let's say you want to exclude a "type" filter

PhotosPicker("Pick Photo",
             selection: $item,
             matching: .any(of: [.images, .not(.videos)])) //<- Use the .not() to exclude filters

Example

Let's take a sample code I wrote:

// Other views...
VStack {
            // Pick either photos or videos
            PhotosPicker("Pick **EITHER** Photos or Videos", //<- Bonus tip: You can use markdowns in swift
                         selection: $item,
                         matching: .any(of: [.images, .videos]))
            
            // Filter out photos with the .not() function
            PhotosPicker("Pick **ONLY** Videos",
                         selection: $item,
                         matching: .any(of: [.videos, .not(.images)]))
        }

Results

Simulator Gallery variations of PhotoPicker in app
enter image description here enter image description here

You can find the Apple documentation on the View here

like image 74
Visal Rajapakse Avatar answered Sep 05 '25 00:09

Visal Rajapakse