如何将数据从Cloud Firestore快速保存到变量中?

时间:2020-07-23 19:45:59

标签: swift firebase google-cloud-firestore

我想将文档中的特定字段保存到变量中。到目前为止,我的代码:

func getDocument(path: String, field: String? = "nil") -> some Any{
    var returnVar : Any = "DEFAULT VAL"
    var db: Firestore!
    db = Firestore.firestore()
    
    let docRef = db.document(path)
    docRef.getDocument { (document, error) in
        if let document = document, document.exists {
            if(field != "nil"){
                let property =  document.get("phrase") ?? "nil"
                returnVar = property
                return;
            }
            else{
                let dataDescription = document.data().map(String.init(describing:)) ?? "nil"
                returnVar = dataDescription
                return;
            }
        } else {
            print("Document does not exist")
            returnVar = -1
            return;
        }
    }
    print("Returned val: " + (returnVar as! String))
    return returnVar;
}

但是,似乎我的getDocument方法在从firebase读取数据之前就返回了(来自纯OOP领域,我不知道这是怎么发生的)从调试看来,执行似乎只是跳过了整个docRef.getDocument代码,跳转到return语句。只有在函数返回后,docRef.getDocument块中的代码才会被执行(什么?已经返回的函数中的代码如何继续执行?)。

如何将特定字段存储在变量中并返回它?

1 个答案:

答案 0 :(得分:4)

那是因为Firestore函数getDocumentasynchronous函数,它立即返回,然后继续执行其中的代码。如果要从此处返回特定值,则需要使用completion Handler。您的功能可能如下所示。

func getDocument(path: String, field: String? = "nil", completion:@escaping(Any)->()) {
var returnVar : Any = "DEFAULT VAL"
var db: Firestore!
db = Firestore.firestore()

let docRef = db.document(path)
docRef.getDocument { (document, error) in
    if let document = document, document.exists {
        if(field != "nil"){
            let property =  document.get("phrase") ?? "nil"
            returnVar = property
            completion(returnVar)
        }
        else{
            let dataDescription = document.data().map(String.init(describing:)) ?? "nil"
            returnVar = dataDescription
            completion(returnVar)
        }
    } else {
        print("Document does not exist")
        returnVar = -1
        completion(returnVar)
      }
    }
  }

然后在viewDidLoad或类似的其他任何函数中调用该函数。

getDocument(path: path, field: field){(value) in
    print(value)
}

您可以查看有关Completion Handlers here

的更多信息