Invoke PhotoPicker Programmatically?
Asked Answered
S

1

9

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!

Sb answered 30/12, 2022 at 23:22 Comment(0)
A
24

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
    }
}
Anselm answered 20/1, 2023 at 9:30 Comment(2)
This is great, thank you. I watched 3 different tutorial videos and read another 4, and they all demonstrate it using a clickable button. Even Apple's tutorial only demos with a button. Your answer is the only one that mentions a programmable way to invoke it. Works perfectly.Solidarity
don't forget 'import PhotosUI'Chastise

© 2022 - 2024 — McMap. All rights reserved.