SwiftUI Custom Alert action block does not execute

145 Views Asked by At

I want to achieve an alert that has a text field embedded in it WITHOUT the help of iOS 16. It went smoothly until I wanted to update a variable when I press one of the buttons.

Currently, I have the custom alert code, which is straight up copied from a YouTube video that works perfectly:

extension View {
    func alertTF(title: String, message: String, hintText: String, primaryTitle: String, secondaryTitle: String, primaryAction: @escaping (String) -> (), secondaryAction: @escaping () -> () ) {
        let alert = UIAlertController(title: title, message: message, preferredStyle: .alert)
        alert.addTextField { field in
            field.placeholder = hintText
        }
        
        alert.addAction(.init(title: secondaryTitle, style: .cancel, handler: { _ in
            secondaryAction()
        }))
        
        alert.addAction(.init(title: primaryTitle, style: .default, handler: { _ in
            if let text = alert.textFields?[0].text {
                primaryAction(text)
            } else {
                primaryAction("")
            }
        }))
        
        rootController().present(alert, animated: true, completion: nil)
    }
    
    func rootController() -> UIViewController {
        guard let screen = UIApplication.shared.connectedScenes.first as? UIWindowScene else {
            return .init()
        }
        
        guard let root = screen.windows.first?.rootViewController else {
            return .init()
        }
        
        return root
    }
}

and here's the SwiftUI code that calls it:

@State private var submittedExportRequest = false

...

VStack {
     ARViewWrapper(submittedExportRequest: $submittedExportRequest, exportedURL: $exportedURL, submittedName: submittedName)
         .ignoresSafeArea()
                
     Button("Export") {
        alertTF(title: "Save as", message: "Please enter your file name", hintText: "my_file", primaryTitle: "Save", secondaryTitle: "cancel") { text in
        print(text)
        submittedName = text
        
        // Does not update my binding value.
        submittedExportRequest.toggle()

        } secondaryAction: {
            print("cancelled")
        }
    }
}

and a UIViewRepresentable View that is supposed to be called when one of the button is pressed:

@Binding var submittedExportRequest: Bool
@Binding var exportedURL: URL?
var submittedName: String

...

func updateUIView(_ uiView: ARView, context: Context) {
        
        // This does not get executed 
        if submittedExportRequest {
            ...
        }
    }

As you can see, the alert does not update my binding that was supposed to be passed in and refresh my UIViewRepresentable. Would be grateful if anyone could offer advice on how to approach this. Thanks!

0

There are 0 best solutions below