Gary
Gary

Reputation: 37

retrieve values from firestore's struct in swift

I'm querying some data from my firestore,and I put it in my Usersdata, but I dont know how to get my values from Usersdata.

Please help me to query my data!

This is my struct base on Firestroe example

struct Usersdata {
let uid:String?
let facebook:String?
let google:String?
let name:String?
let age:Int?
let birthday:String?
let smokeage:Int?
let smokeaddiction:Int?
let smokebrand:String?
let gold:Int?
let score:Int?
let fish:Int?
let shit:Int?
let userimage:String?
init?(dictionary: [String: Any]) {
    guard let uid = dictionary["uid"] as? String else { return nil }
    self.uid = uid
    self.facebook = dictionary["facebook"] as? String
    self.google = dictionary["google"] as? String
    self.name = dictionary["name"] as? String
    self.age = dictionary["age"] as? Int
    self.birthday = dictionary["birthday"] as? String
    self.smokeage = dictionary["smokeage"] as? Int
    self.smokeaddiction = dictionary["smokeaddiction"] as? Int
    self.smokebrand = dictionary["smokebrand"] as? String
    self.gold = dictionary["gold"] as? Int
    self.score = dictionary["score"] as? Int
    self.fish = dictionary["fish"] as? Int
    self.shit = dictionary["shit"] as? Int
    self.userimage = dictionary["userimage"] as? String
    }   
}

this is my function to query data from firebase

 func test(schema:String , collection:String , document : String){
    let queryRef = db.collection("Users").document(userID).collection(collection).document(document)
    queryRef.getDocument { (document, error) in
        if let user = document.flatMap({
            $0.data().flatMap({ (data) in
                return Usersdata(dictionary: data)
            })
        }) {
            print("Success \(user)")
        } else {
            print("Document does not exist")
        }
    }
}

Upvotes: 0

Views: 782

Answers (1)

Jay
Jay

Reputation: 35658

I think you are asking how to work with a structure with Firebase data. Here's a solution that will read in a known user, populate a structure with that data and then print the uid and name.

Assume a stucture

Users
  uid_0
    name: "Henry"

and then a structure to hold that data

struct Usersdata {
    let uid:String?
    let user_name:String?
    init(aDoc: DocumentSnapshot) {
        self.uid = aDoc.documentID
        self.user_name = aDoc.get("name") as? String ?? ""
    }
}

and a function to read that user, populate the struct and print out data from the struct

func readAUser() {
    let docRef = self.db.collection("Users").document("uid_0")
    docRef.getDocument { (document, error) in
        if let document = document, document.exists {
            let aUser = Usersdata(aDoc: document)
            print(aUser.uid, aUser.user_name)
        } else {
            print("Document does not exist")
        }
    }
}

and the output

uid_0 Henry

Upvotes: 1

Related Questions