I have a login screen on which I programmatically push to the next screen using a hidden NavigationLink tied to a state variable. The push works, but it seems to push twice and pop once, as you can see on this screen recording:
This is my view hierarchy:
App
NavigationView
LaunchView
LoginView
HomeView
App:
var body: some Scene {
WindowGroup {
NavigationView {
LaunchView()
}
.navigationBarBackButtonHidden(true)
.navigationBarHidden(true)
.environmentObject(cache)
}
}
LaunchView:
struct LaunchView: View {
#EnvironmentObject var cache: API.Cache
#State private var shouldPush = API.shared.accessToken == nil
func getUser() {
[API call to get user, if already logged in](completion: { user in
if let user = user {
// in our example, this is NOT called
// thus `cache.user.hasData` remains `false`
cache.user = user
}
shouldPush = true
}
}
private var destinationView: AnyView {
cache.user.hasData
? AnyView(HomeView())
: AnyView(LoginView())
}
var body: some View {
if API.shared.accessToken != nil {
getUser()
}
return VStack {
ActivityIndicator(style: .medium)
NavigationLink(destination: destinationView, isActive: self.$shouldPush) {
EmptyView()
}.hidden()
}
.navigationBarTitle("")
.navigationBarHidden(true)
}
}
This is a cleaned version of my LoginView:
struct LoginView: View {
#EnvironmentObject var cache: API.Cache
#State private var shouldPushToHome = false
func login() {
[API call to get user](completion: { user in
self.cache.user = user
self.shouldPushToHome = true
})
}
var body: some View {
VStack {
ScrollView(showsIndicators: false) {
// labels
// textfields
// ...
PrimaryButton(title: "Anmelden", action: login)
NavigationLink(destination: HomeView(), isActive: self.$shouldPushToHome) {
EmptyView()
}.hidden()
}
// label
// signup button
}
.navigationBarTitle("")
.navigationBarHidden(true)
}
}
The LoginView itself is child of a NavigationView.
The HomeView is really simple:
struct HomeView: View {
#EnvironmentObject var cache: API.Cache
var body: some View {
let user = cache.user
return Text("Hello, \(user.contactFirstname ?? "") \(user.contactLastname ?? "")!")
.navigationBarTitle("")
.navigationBarHidden(true)
}
}
What's going wrong here?
Update:
I've realized that the issue does not occur, when I replace LaunchView() in App with LoginView() directly. Not sure how this is related...
Update 2:
As Tushar pointed out below, replacing destination: destinationView with destination: LoginView() fixes the problem – but obviously lacks required functionality.
So I played around with that and now understand what's going on:
LaunchView is rendered
LaunchView finds there's no user data yet, so pushes to LoginView
upon user interaction, LoginView pushes to HomeView
at this point, the NavigationLink inside LaunchView is called again (idk why but a breakpoint showed this), and since there is user data now, it renders the HomeView instead of the LoginView.
That's why we see only one push animation, and the LoginView becoming the HomeView w/o any push animation, b/c it's replaced, essentially.
So now the objective is preventing LaunchView's NavigationLink to re-render its destination view.
I was finally able to resolve the issue thanks to Tushar's help in the comments.
Problem
The main problem lies in the fact I didn't understand how the environment object triggers re-renders. Here's what was going on:
LaunchView has the environment object cache, which is changed in LoginView, when we set cache.user = user.
That triggers the LaunchView to re-render its body.
since the access token is not nil after login, on each re-render, the user would be fetched from the API via getUser().
disregarding the fact whether that api call yields a valid user, shouldPush is set to true
LaunchView's body is rendered again and the destinationView is computed again
since now the user does have data, the computed view becomes HomeView
This is why we see the LoginView becoming the HomeView w/o any push – it's being replaced.
at the same time, the LoginView pushes to HomeView, but since that view is already presented, it pops back to its first instance
Solution
To fix this, we need to make the property not computed, so that it only changes when we want it to. To do so, we can make it a state-managed variable and set it manually in the response of the getUser api call:
Excerpt from LaunchView:
// default value is `LoginView`, we could also
// set that in the guard statement in `getUser`
#State private var destinationView = AnyView(LoginView())
func getUser() {
// only fetch if we have an access token
guard API.shared.accessToken != nil else {
return
}
API.shared.request(User.self, for: .user(action: .get)) { user, _, _ in
cache.user = user ?? cache.user
shouldPush = true
// manually assign the destination view based on the api response
destinationView = cache.user.hasData
? AnyView(HomeView())
: AnyView(LoginView())
}
}
var body: some View {
// only fetch if user hasn't been fetched
if cache.user.hasData.not {
getUser()
}
return [all the views]
}
Related
I have a swift UI view that when tapped should show a progress view:
struct ProjectItem: View {
#EnvironmentObject var controller: ProjectController
#State var showLoadingIcon: Bool = false
let document: Document
var body: some View {
VStack {
ZStack {
Text(document.name).font(Interface.Text.PopoverDialogLabel)
Text(document.editTime.toString(true)).font(.caption2).foregroundColor(.gray)
if showLoadingIcon {
ProgressView()
}
}
.padding(Interface.Sizes.StandardPadding)
.if(controller.editedDocumentID == nil) { $0.onTapGesture(count: 1, perform: {
// Open Project
showLoadingIcon = true //This occours after TransitionView
controller.openDocument(document: document)
TransitionView() //this happens before the progressView is shown
})}
}
}
When tapped it can take a couple of seconds to open the document and we would like to show a progressView to the user to display something is happening. However the progressView will only show to the user after the document has loaded.
In the view controller the openDoucment simply calls part of an app:
func openDocument(document: Document) {
app.setProject(document.id) //this takes a few seconds
}
app.setProject(document.id) is on the main thread and ideally, this will be moved to its own thread in the future but we cannot for now.
How can the progress view be displayed before the loadDocument call is made?
I have tried to wrap the following into a Task{}
controller.openDocument(document: document)
TransitionView()
I have also made the openDocument call async and sync which did not fix the issue.
I have also disabled the transitionView call and can see from my breakpoints that controller.openDocument call occurs before the
if showLoadingIcon {
ProgressView()
}
switches to showLoadingicon is switched - meaning that showLoadingIcons is checked by the app after controller.openDocument is completed and is shown.
The problem is that you are doing too much controller stuff in the view. Move the logic to control the view into the project controller.
In the controller – assuming it conforms to ObservableObject – add an enum and a state variable
enum ProjectState {
case idle, loading, loaded
}
#Published var state : ProjectState = .idle
and you have to make setProject really asynchronous to indicate when loading the data has been finished
func openDocument(document: Document) {
Task { #MainActor in
state = .loading
await app.setProject(document.id)
state = .loaded
}
}
Otherwise use a completion handler. As the code of setDocument is not part of the question you have to change it yourself.
In the view the conditional view modifier .if is very bad practice because it's not needed at all. You can disable the tap gesture much simpler with .allowsHitTesting. To show the appropriate view switch on controller.state
struct ProjectItem: View {
#EnvironmentObject var controller: ProjectController
let document: Document
var body: some View {
VStack {
ZStack {
Text(document.name).font(Interface.Text.PopoverDialogLabel)
Text(document.editTime.toString(true)).font(.caption2).foregroundColor(.gray)
switch controller.state {
case .idle: EmptyView()
case .loading: ProgressView()
case .loaded: TransitionView()
}
}
}
.padding(Interface.Sizes.StandardPadding)
.allowsHitTesting(controller.editedDocumentID == nil)
.onTapGesture {
controller.openDocument(document: document)
}
}
}
Using StateObject allows my view to rerender correctly after getting data asynchronously but ObservedObject does not, why?
I have two swiftui views. First is the root App view and the second is the one consuming an ObservedObject view model.
From the root view I create a ViewModel with a firebase object ID for the second view and pass it in. When the second view appears I'd like to then send a request to Firebase to retrieve some data. While the data is being retrieved I show a 'loading' screen.
When I use ObservedObject my second view never rerenders after the data is retrieved. Using StateObject though fixes the issue but I'm not sure why.
I think I understand the differences between ObservedObject and StateObject having read the docs. But not sure how the differences apply to my case since I don't think the root view should be rerendering and recreating the ViewModel I created there and passed to the second view.
There is a Login view which forces the RootView to rerender after login but from what I know, the SecondView still shouldn't be rendered more than once.
https://www.avanderlee.com/swiftui/stateobject-observedobject-differences/
RootView
#main
struct MyApp: App {
#ObservedObject private var userService = UserService()
init() {
FirebaseApp.configure()
}
var body: some Scene {
WindowGroup {
NavigationView {
Group {
if (userService.currentUser != nil) {
SecondView(secondViewModel: SecondViewModel(somethingId: "someIdGoesHere"))
} else {
LoginView()
}
}
.environmentObject(userService)
}
}
}
}
View Model
class SecondViewModel: ObservableObject {
#Published private(set) var thing: Thing? = nil
private let thingService = ThingService()
private let thingId: String
init(thingId: String) {
self.thingId = thingId
}
func load() async {
self.thing = await thingService.GetThing(thingId: thingId) // Async call to firebase
}
}
Second View
struct SecondView: View {
// Task runs to completion but 'Loading...' never goes away.
#ObservedObject var secondViewModel: SecondViewModel
var body: some View {
VStack(spacing: 5) {
if let thingText = secondViewModel.thing {
Text(thingText)
} else {
Text("Loading...")
}
}
.onAppear {
Task {
await secondViewModel.load()
}
}
}
}
I am using SwiftUI and Firebase Realtime Database within my project and whenever I try changing the contents of my database, and then redirect the user to the next view, the view changes briefly and then get redirected back.
Here is a simplified version of my code to help you understand:
import SwiftUI
import Firebase
import FirebaseDatabase
struct someView: View {
private var randomText = ["hello", "world"]
#State private var showNextView = false
var ref: DatabaseReference!
init() {
ref = Database.database!.reference()
}
var body: some View {
ZStack {
NavigationLink("", destination: nextView(), isActive: $showNextView)
Button {
save()
self.showNextView.toggle()
} label : {Text("Save")}
}
}
func save() {
self.ref.child("users/\(Auth.auth().currentUser!.uid)/someName").setValue(randomText)
}
}
struct nextView: View {
var body: some View {
ZStack {
Text("This is the next view")
}
}
}
When I click the button within someView, the array is saved correctly in the database. I then get redirected to nextView where I see the text "This is the next view" - as expected. However, this only shows briefly and then the view jumps back to someView again. I am unsure why this is and cannot find any information as to how to fix it.
I assume this happens because click handled and by Button and by NavigationLink which right under button, so try to hide link completely to make it activate only programmatically, like
ZStack {
NavigationLink(destination: nextView(), isActive: $showNextView) {
EmptyView() // << here !!
}.disabled(true) // << here !!
Button {
save()
self.showNextView.toggle()
} label : {Text("Save")}
}
You need to wrap your ZStack inside a NavigationView if you want to use NavigationLink.
NavigationView {
ZStack {
NavigationLink("", destination: nextView(), isActive: $showNextView)
Button {
save()
self.showNextView.toggle()
} label : {Text("Save")}
}
}
So I've made a Button view in my body and I have set it's action to a Google Sign In action, but I want it to also transition to a new view when the sign in flow is completed. The problem is that I have set the label of the button to a Navigation Link and when I click it, it directly transitions to a next view. How can I delay the transition? For context, VoucherView is the next view I want to transition to.
Button {
guard let clientID = FirebaseApp.app()?.options.clientID else { return }
// Create Google Sign In configuration object.
let config = GIDConfiguration(clientID: clientID, serverClientID: GlobalConstants.BACKEND_SERVER_REQUEST_ID_TOKEN)
guard let presenter = CommonHelper.GetRootViewController() else {return}
// Start the sign in flow!
GIDSignIn.sharedInstance.signIn(with: config, presenting: presenter) {user, error in
if let error = error {
print (error.localizedDescription)
return
}
guard
let authentication = user?.authentication,
let idToken = authentication.idToken
else {
print ("Something went wrong!")
return
}
print (authentication)
print (idToken)
let credential = GoogleAuthProvider.credential(withIDToken: idToken,
accessToken: authentication.accessToken)
print (credential)
UserManager.shared.firebaseAuthentication(credential: credential)
signed = true
}
} label: {
NavigationLink {
VoucherView()
} label: {
Text("Sign In")
}
}
Edit: After I tried using isValid as a #State variable, after every cycle of SignIn and SignOut the screen goes down.
First SignIn
FirstSignOut
SecondSignIn
SecondSignOut
Instead of using NavigationLink inside your Button, you can use a NavigationLink with an EmptyView for a label and then activate it programmatically with the isActive parameter.
See the following example -- the Google Sign In process is replaced by just a simple async closure for brevity.
struct ContentView: View {
#State private var navigateToNextView = false
var body: some View {
NavigationView {
VStack {
Button {
DispatchQueue.main.asyncAfter(deadline: .now() + 1) {
navigateToNextView = true
}
} label: {
Text("Sign in")
}
NavigationLink(destination: View2(), isActive: $navigateToNextView) { EmptyView()
}
}
}.navigationTitle("Test")
}
}
struct View2 : View {
var body: some View {
Text("Next view")
}
}
A couple more notes:
Note that there has to be a NavigationView (make sure it's just one) in the hierarchy for this to work
In general, async work is better done in an ObservableObject than in a View. You can consider moving your login function to an ObservableObject and making the navigateToNextView a #Published property on that object.
I'm downloading data from FireStore. Data is retrieved perfectly. I have the data and can print information. The issue is, when I tap on a text/label to push to the intended view, I perform the function using the .onAppear function. My variables, from my ObservableClass are #Published. I have the data and can even set elements based on the data retrieved. I'm using the MVVM approach and have done this a plethora of times throughout my project. However, this is the first time I have this particular issue. I've even used functions that are working in other views completely fine, yet in this particular view this problem persists. When I load/push this view, the data is shown for a split second and then the view/canvas is blank. Unless the elements are static i.e. Text("Hello World") the elements will disappear. I can't understand why the data just decides to disappear.
This is my code:
struct ProfileFollowingView: View {
#ObservedObject var profileViewModel = ProfileViewModel()
var user: UserModel
func loadFollowing() {
self.profileViewModel.loadCurrentUserFollowing(userID: self.user.uid)
}
var body: some View {
ZStack {
Color(SYSTEM_BACKGROUND_COLOUR)
.edgesIgnoringSafeArea(.all)
VStack(alignment: .leading) {
if !self.profileViewModel.isLoadingFollowing {
ForEach(self.profileViewModel.following, id: \.uid) { user in
VStack {
Text(user.username).foregroundColor(.red)
}
}
}
}
} .onAppear(perform: {
self.profileViewModel.loadCurrentUserFollowing(userID: self.user.uid)
})
}
}
This is my loadFollowers function:
func loadCurrentUserFollowing(userID: String) {
isLoadingFollowing = true
API.User.loadUserFollowing(userID: userID) { (user) in
self.following = user
self.isLoadingFollowing = false
}
}
I've looked at my code that retrieves the data, and it's exactly like other features/functions I already have. It's just happens on this view.
Change #ObservedObject to #StateObject
Update:
ObservedObject easily gets destroyed/recreated whenever a view is re-created, while StateObject stays/exists even when a view is re-created.
For more info watch this video:
https://www.youtube.com/watch?v=VLUhZbz4arg
It looks like API.User.loadUserFollowing(userID:) may be asynchronous - may run in the background. You need to update all #Published variables on the main thread:
func loadCurrentUserFollowing(userID: String) {
isLoadingFollowing = true
API.User.loadUserFollowing(userID: userID) { (user) in
DispatchQueue.main.async {
self.following = user
self.isLoadingFollowing = false
}
}
}
You might need to add like this: "DispatchQueue.main.asyncAfter"
.onAppear {
DispatchQueue.main.asyncAfter(deadline: .now() + 1.0) {
self.profileViewModel.loadCurrentUserFollowing(userID: self.user.uid)
}
}