SwiftUI navigationLink with completion handler

Hello,


I'd like to know if and how I can include a completion handler to a navigationLink. Given the following:


struct SignupNavLink: View {
    var body: some View {
        NavigationLink(destination: HomeView()) { // Only trasition after the account has been created
            Text("Signup")
                .font(.headline)
                .frame(minWidth: 0, maxWidth: .infinity)
                .padding()
                .background(Color.gray)
                .foregroundColor(.black)
        }
    }
}


Before having the NavigationLink calling on HomeView() I would like to call the following function which would create a user account.


func registerNewUser() {
    let privateKeyA = Curve25519.Signing.PrivateKey()
    let publicKeyA = privateKeyA.publicKey.rawRepresentation.base64EncodedString()
    print(publicKeyA)
    let user = User()
    user.password = "******"
    user.name = "Test"
    user.setProperty(propertyName: "userKey", propertyValue: publicKeyA)
   
    Backendless.shared.userService.registerUser(user: user, responseHandler: { registeredUser in
        print("User registration completed")
       
    }, errorHandler: { fault in
        print("Error: \(fault.message ?? "")")
    })
}

Replies

You can use your custom navigation flow instead of default. In order to achieve this, use another NavigationLink init method with isActive binding which you will toggle on the Tap gesture of the Text just after executing registerNewUser() method.


Here is code example:


struct SomeList: View {
    
    @State private var shouldTransit: Bool = false
    
    var body: some View {

        NavigationView {        
            NavigationLink(destination: HomeView()), isActive: $shouldTransit) {
                Text("Signup")
                    .font(.headline)
                    .frame(minWidth: 0, maxWidth: .infinity)
                    .padding()
                    .background(Color.gray)
                    .foregroundColor(.black)
                    .onTapGesture {
                        self.registerNewUser()
                        self.shouldTransit = true
                }
            }
        }      
    }
    
    func registerNewUser() {
        print("Registered")
    }
}