skip to Main Content
let db = Firestore.firestore()
let docRef = db.collection("users").document(result!.user.uid)

docRef.getDocument { (document, error) in
    if let document = document, document.exists {
        let dataDescription = document.data().map(String.init(describing:)) ?? "nil"
        print("Document data: (dataDescription)")
        print()
        
    } else {
        print("Document does not exist")
    }
}

print("Document data: (dataDescription)") outputs the following:

Document data: ["uid": LjqBXo41qMStt89ysQ4I9hxla2h1, "firstname": Tim, "lastname": Dorsemagen]

How can I extract each value such as the uid, the firstname and the lastname from dataDescription?

2

Answers


  1. There are several ways to accomplish this. One of the most easily understood would be to break the string down in sections. Assuming you only want the values rather than their keys:

    let values  = dataDescription
       .dropFirst()
       .dropLast()
       .components(separatedBy: ",")
       .map{$0.components(separatedBy: ":")}
       .map{$0.last!.trimmingCharacters(in: .whitespaces)}
    
    print(values) //["LjqBXo41qMStt89ysQ4I9hxla2h1", "Tim", "Dorsemagen"]
    
    Login or Signup to reply.
  2. Firestore has everything needed to easily get components of a document. Here’s an asynchronous example of reading a users name from a document and returning it

    func getUserAsync() async -> String{
        let usersCollection = self.db.collection("users") //self.db is my Firestore
        let thisUserDoc = usersCollection.document("uid_0")
        let document = try! await thisUserDoc.getDocument()
        
        let name = document.get("name") as? String ?? "No Name"
        
        return name
    }
    

    if you want to use Codable (advised! See Mapping Firestore Data), this works for printing the name (can also be combined with the above solution)

    func readUser() {
        let usersCollection = self.db.collection("users") //self.db is my Firestore
        let thisUserDoc = usersCollection.document("uid_0")
    
        thisUserDoc.getDocument(completion: { document, error in
            if let doc = document {
                let user = try! doc.data(as: UserCodable.self)
                print(user.name) //assume the UserCodable object has a name property
            }
        }
    }
    

    or just a regular old read of a document and print the name

    func readUser() {
        let usersCollection = self.db.collection("users") //self.db is my Firestore
        let thisUserDoc = usersCollection.document("uid_0")
    
        thisUserDoc.getDocument(completion: { document, error in
            let name = document?.get("name") as? String ?? "No Name"
            print(name)
        })
    }
    

    *note: no error checking and I am force unwrapping options. Don’t do that.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search