将Firebase Firestore文档值分配给swift变量

时间:2020-07-08 20:09:02

标签: swift firebase google-cloud-firestore

因此,我试图从Firebase Firestore提取数据并将其放入函数中的局部变量中。在函数内部,我为一个名称创建了一个变量,该变量应该包含从Firebase获取的用户名的值。问题是,赋予nameData值(数据库的名称)的变量名称实际上从未被更改。如何从数据库中获取名称并将其放入变量中?

public func fetchName(email: String) -> String {
        var name: String = "FIRST VALUE"
        
        database.collection(workerCollection).document(email).getDocument() {(querySnapshot, error) in
            if let error = error {
                print("Error getting documents: \(error)")
            } else {
                //get info about user
                if (querySnapshot != nil && querySnapshot!.exists){
                    let documentData = querySnapshot!.data()!
                    if let nameData = (documentData["Name"] as! String?){
                        name = nameData
                    }
                    print(name)
                }
            }
        }
        
    return name
}

2 个答案:

答案 0 :(得分:1)

在函数中添加完成处理程序以获取名称。像这样修改您的功能!

public func fetchName(email: String, Completion:@escaping((String)->()) {
    
    database.collection(workerCollection).document(email).getDocument() {(querySnapshot, error) in
        if let error = error {
            print("Error getting documents: \(error)")
        } else {
            //get info about user
            if (querySnapshot != nil && querySnapshot!.exists){
                let documentData = querySnapshot!.data()!
                if let nameData = (documentData["Name"] as! String?){
                    Completion(nameData)
                }
            }
        }
     }
  }

然后在viewDidLoad或您喜欢的任何地方调用该函数。

fetchName(email: "a@b.com") { (name) in
        print(name)
    }

答案 1 :(得分:0)

尝试一下:

public func fetchName(email: String) -> String? {
        var name: String?
        
        name = database.collection(workerCollection).whereField("emailField", isEqualTo: email)

        dispatchQueue.main.async {
            return name
        }
}