Push View Controller in SwiftUI

I need to push to other view controller when I get error from API call. All SwiftUI examples push are using navigation view and navigation link. I can't seem to make it work to push without action button.
Answered by mtsrodrigues in 614994022
You can use the isActive parameter of NavigationLink to bind a property and trigger the push changing the property value to true:

Code Block swift
struct ContentView: View {
    @State private var isActive = false
    var body: some View {
        NavigationView {
            VStack {
                Button("Present") {
                    isActive = true
                }
                NavigationLink(destination: Color.red, isActive: $isActive) { }
            }
        }
    }
}


I'm using a Button action to change the value but you can do it in the error handling for example.
Accepted Answer
You can use the isActive parameter of NavigationLink to bind a property and trigger the push changing the property value to true:

Code Block swift
struct ContentView: View {
    @State private var isActive = false
    var body: some View {
        NavigationView {
            VStack {
                Button("Present") {
                    isActive = true
                }
                NavigationLink(destination: Color.red, isActive: $isActive) { }
            }
        }
    }
}


I'm using a Button action to change the value but you can do it in the error handling for example.
thank you @mtsrodrigues, that will be fine to show error message in that particular View. But what if we have a bunch of API calls from different source and we would want to centralized the "push to error view" from that global network call?
You can implement your error view in your root view with an if statement and show/hide the error view using either an environment object or a shared model/viewmodel property. This way you can control it directly from any view and/or from the model/viewmodel itself.
Yeah, I guess currently the only approach is to centralised all the logic in the root view. Thank you mjfigueroa.
Push View Controller in SwiftUI
 
 
Q