In my application I start with a LoginView which makes an API call to the backend for authentication. In case this is successfull (in a completion handler, i want to show the FeedView().
With UIKit this is all pretty simple trying to figure out how to do this with SwiftUI.
So How can I show a new View programmatically (I don’t have a NavigationView)?
3
Answers
You can have a conditional view like so:
Notice how we use
@State
to switch between what view is shown.If you don’t want to use a
NavigationView
, you have several options:A SwiftUI-native style would be simply to have a parent view which
holds your view, and other views. You can have a property on a
shared
ViewModel
and the parent view can return a different childview depending on the value of the view model
Displaying a new view modally (this is easiest)
Using UIKit navigation – this is my preferred method in complex apps where you can simply navigate around the app using UIViewControllers, with a SwiftUI view pinned to the edges
I can go into more detail on any of these, with some sample code from my own projects, if you would like. Option 1 is probably the most natural for SwiftUI and you can even animate the transitions pretty nicely with things like
matchedGeometryView
if you use this option.You could use EnvironmentObject to control your user Session, the example below is with Firebase Authentication. Take care you need to add an environmentObject in your parent view.
Main:
ContentView: access your environment var
Sample Session Manager (Firebase sample, if you have another backend you need to add your logic). Then is possible to call logout wherever you want in your app, this action change ContentView State and display LoginView: