I followed the official SwiftUI tutorial - https://developer.apple.com/tutorials/swiftui/composing-complex-interfaces to learn how to use SwiftUI. In my app, I want to build login functionality. For that, I have a login screen with a button. On pressing it, a request is sent out and only after receiving the response, I want to navigate to the next screen. The same principle is needed for logging out. After searching the web, the following approach is suggested on many pages, where a state variable is changed by the button action to trigger the empty navigation event.
@State var selection: Int? = nil
...
Button("Login", action: {
viewModel.login(name: username, password: password) { didSucceed in
if didSucceed {
self.selection = 1
} else {
print("Login error, TODO: proper handling")
}
}
})
NavigationLink(destination: MapScreen(), tag: 1, selection: $selection) { EmptyView() }
.hidden()
Is this the officially recommended way of navigating programmatically in SwiftUI or does a more convenient way exist?