我正在查询Firestore中的一些数据,并将其放入Usersdata中,
但我不知道如何从Usersdata获取我的值。

请帮我查询我的数据!

这是我基于Firestroe示例的结构

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
    }
}


这是我从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")
        }
    }
}

最佳答案

我认为您在问如何使用Firebase数据处理结构。这是一个可以读取已知用户的解决方案,使用该数据填充结构,然后输出uid和名称。

假设一个结构

Users
  uid_0
    name: "Henry"


然后是一个保存数据的结构

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


以及读取该用户,填充结构并从结构中打印出数据的功能

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")
        }
    }
}


和输出

uid_0 Henry

关于ios - 快速从firestore的结构中检索值,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/52973289/

10-11 14:42
查看更多