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?'
CodePudding user response:
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 |
---|---|
You can find the Apple documentation on the View here