Home > Back-end >  SwiftUI & Firestore
SwiftUI & Firestore

Time:11-24

I am wanting to use Firestore to retrieve user info and other data linked to that user once they have logged in via firebase auth. On the home page of the app I use .onAppear{ pulluserData() }. I understand that Firestore functions are asynchronous so how can I wait for this data to be pulled before displaying it to the user on the home screen?

Here is my function to check the database:

func checkDatabase() async {
        //Function that will check the database. Will be good to add a listener eventually

        if self.pullUserData{
            await dbm.readUser(userID: "VSWAq7QCw3dbGYwMdtClbbANGVe2")

        }
}

and the actual database function:

func readUser(userID: String)async{
        //Function that will be used to read user info from the database
        let userRef = database.collection("users")
      
        do{
            let doc = try await userRef.document(userID).getDocument().data()
            print("The doc is: ")
            print(doc as Any)
        }
        catch {
            
        }
        
    }

CodePudding user response:

There are a number of ways to do this but the two most common ways are to (1) use a launch screen to indicate a loading state that disappears to a view identical to the launch screen (to continue the appearance of loading) that is only removed when the database returns (i.e. Twitter); (2) load the user right into the app and allow them to move freely while either indicating that data is loading or displaying cached data.

Remember that Firestore maintains a local cache on the device which means that data will be available immediately when the app launches. This data may be out of sync with the server but it will update as soon as the app establishes a connection with Firestore, which is usually instant. What I would recommend is launching the user right into the app without the use of a loading screen and relying on the cached data to get the UI up as fast as possible.

And if we're only talking about user-specific data (data that is specific to the user that the user has full control over) then that data will only change when the user changes it, which would have been the last time they used the app, which means that the locally-cached data on their device (assuming they use only one device) will always reflect the state of the server (in theory, anyway). And if it doesn't then it doesn't; the fresh data will update instantly anyway.

You may then wonder what happens if the user launches the app without connection. In that case, the cached data is displayed and the user is almost none the wiser. And because Firestore is offline capable, the user can freely edit their data and it will write to the server when connection eventually establishes.

  • Related