Home > Enterprise >  SwiftUI Delay on view variable
SwiftUI Delay on view variable

Time:12-26

I got a class with a function that gets the username for printing it on the view. It works, but I got a delay of nearly a second where the username is not seen.

here the class :

   class ViewModel: ObservableObject {


@Published var username: String = ""





func benutzerdaten_accountview (email: String) -> String {
    let db = Firestore.firestore()
    let docRef = db.collection("Nutzer").document(email)
    docRef.getDocument{ (document, error) in
        
        if let document = document, document.exists{
            self.username = (document.data()!["username"] as? String)!
    }
   }
    return username
  }

}

This is how I print it on the view :

struct AccountView: View{

@ObservedObject var model = ViewModel()
@Binding var tabSelection: Int
var email: String = (Auth.auth().currentUser?.email)!

var body: some View {
    
        VStack{
            
            Text("Hallo, \(model.benutzerdaten_accountview(email: email).description)")
         ...

CodePudding user response:

In benutzerdaten_accountview(), you can't return username because it isn't already set yet. The username is set in an asynchronous closure.

You are already setting username in the callback closures already, so that's good. What you need to do now is just call the method in onAppear(perform:) so it shows as soon as AccountView loads.

The changing of username will publish an update to update the view again, when it is ready. Fetching data from an API can take time, especially when you have cold-starts.

Firstly, remove the return and the return type in that benutzerdaten_accountview() method. This is no longer needed. Rest of code:

struct AccountView: View {
    @ObservedObject var model = ViewModel()
    @Binding var tabSelection: Int
    var email: String = (Auth.auth().currentUser?.email)!

    var body: some View {
        VStack {
            Text("Hallo, \(model.username)")
        }
        .onAppear {
            model.benutzerdaten_accountview(email: email)
        }
    }
}
  • Related