简体   繁体   中英

SwiftUI FireStore - Get Field from Document and display as Text()

I'm very new to SwiftUI so bare with me - it's for a project.

I have stored user's details into my Firestore database which looks like this:

image of database

I want to take the name from the database and display it in a Text("Hello" [name]) I have been able to fetch the name from the database and append it into an array. This function is run when the 'Log in' button is clicked.

The code is as follows:

func getData(){
let docRef = db.collection(FStore.collectionName).document(userID)

docRef.getDocument { (document, error) in
    if let document = document, document.exists {
        if let fetchedName = document.get("name") as? String {
            userArray.append(fetchedName)
            print(userArray)
        }
    }
}

}

When printing userArray, the correct name does print. However I am struggling to display the name outside of the console and on my Text UI field. When I attempt the code below, it gives me an index out of range error.

Text("Hello: \(userArray[0])")

Any help is appreciated / any other methods of retrieving field data from a specific document.

Thanks to @Steve M , it ended up being a kind of silly mistake.

He was right, the display was attempting to read the array before the array had even been populated.

As described in my comments, I called the getData() function then ran code to display the next screen. I wrapped the "display next screen code" in a DispatchQueue to delay the next screen being displayed

DispatchQueue.main.asyncAfter(deadline@ .now() + 1){
nextView = true
}

This ran a 1-second delay before displaying the next screen and successfully displayed the name from the database.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM