我想将文档中的特定字段保存到变量中。到目前为止我的代码:
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 代码并跳转到返回声明。只有在函数返回后,docRef.getDocument块中的代码才会被执行(什么?已经返回的函数中的代码如何继续执行?)。
如何将特定字段存储在变量中并返回它?
那是因为 Firestore 功能getDocument
is an asynchronous
函数会立即返回,然后继续执行其中的代码。如果你想从这里返回一个特定的值,你需要使用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 https://vasundharavision.com/blog/ios/completion-handler-in-swift
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)