Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Invoke PhotoPicker Programmatically?

The SwiftUI PhotoPicker is great for creating a button/label to press & then show a Photo Picker when the label is pressed. However, I'd like to invoke a photo picker not after the Picker's label is pressed, but after a conditional test has passed.

For example, if the user clicks on a button that would invoke a Photo Picker, I'd like to first check to see if the record the image will be attached to has been saved. If the record has been saved, I want to launch the picker. If it hasn't been saved, I'll show an alert asking if they want to save or cancel. If they select save, I'll save the record, THEN I'd like to invoke the photo picker automatically.

So can I invoke the Picker programmatically rather than have the user click it? Thanks for advice!

like image 756
Gallaugher Avatar asked Mar 03 '26 16:03

Gallaugher


1 Answers

From iOS 16 you can do this by using the photosPicker(isPresented:

struct DemoView: View {
    
    @ObservedObject var viewModel: DemoViewModel

    var body: some View {
        VStack {
            Text("Demo Project")
        }
        .photosPicker(isPresented: $viewModel.shouldPresentPhotoPicker, selection: $viewModel.selectedPickerItem)
    }
}

class DemoViewModel: ObservableObject {
    @Published var shouldPresentPhotoPicker = false
    @Published var selectedPickerItem: PhotosPickerItem?

    func saveTheRecord() {
        /// Make an async call, and wait
        shouldPresentPhotoPicker = true // Shows the Picker
    }
}
like image 144
πter Avatar answered Mar 06 '26 14:03

πter