How to check conditions before navigating?

Hi! I used NavigationLink to implement navigation. In some links I want to make sure some conditions are satisified when users tap on it. If the conditions are not satisfied, I want to stop the navigation and give an error message. I could do this in UIKit using shouldPerformSegue delegate function, but don't know how to do it in SwiftUI. Can you tell me some idea about how I can do it?


More details. When user tap the link, I want to let the app download some data from Internet and parse it, such that it can be passed into the next view. If for any reason the download fails (for example, no network connection), I want the app to display an error message without navigating. I want to do the download right before navigation is because I want to let the app download the newest data, and avoid unnecessary downloads.


Thank you!

Answered by Claude31 in 399564022

Did you look at using isActive in the declaration of the link ?


@State var showView = false
...
NavigationLink(destination: MyModal(), isActive: $showView) {
    EmptyView()
}


Get details here:

h ttps://dev.to/gualtierofr/navigation-in-swiftui-1hg2

or

h ttps://medium.com/@karaiskc/programmatic-navigation-in-swiftui-30b75613f285

Accepted Answer

Did you look at using isActive in the declaration of the link ?


@State var showView = false
...
NavigationLink(destination: MyModal(), isActive: $showView) {
    EmptyView()
}


Get details here:

h ttps://dev.to/gualtierofr/navigation-in-swiftui-1hg2

or

h ttps://medium.com/@karaiskc/programmatic-navigation-in-swiftui-30b75613f285

Hi Claude31,


Thank you! Even though it seem counter intuitive to me to make an empty view for the navigationlink itself, and then add a button to trigger it, it works for me.

How to check conditions before navigating?
 
 
Q