我想使用Firestore从函数返回文档。这是我的疑问:
public class func getProductsInShoppingList(name:String = "Default") -> DocumentSnapshot?{
let db = Firestore.firestore()
let defaults = UserDefaults.standard
let userId: String! = defaults.string(forKey: "UserUUID")
var doc:DocumentSnapshot?
db.collection("shoppingLists")
.whereField("users." + userId, isEqualTo: true)
.whereField("name", isEqualTo: name)
.limit(to: 1)
.getDocuments() { (querySnapshot, err) in
if let err = err {
print("Error getting documents: \(err)")
} else {
for document in querySnapshot!.documents {
print("\(document.documentID) => \(document.data())")
doc = document
break
}
}
}
return doc
}
这显然是异步操作。返回和使用文档的正确方法是什么。通知?打回来?感谢
答案 0 :(得分:2)
在DidLoad中只需添加一个观察者
override func viewDidLoad()
{
super.viewDidLoad()
//Add notification Observer to get status out of Async mode
NotificationCenter.default.addObserver(self, selector: #selector(loadList), name: NSNotification.Name(rawValue: "DocumentReceived"), object: nil)
}
现在你的功能
public class func getProductsInShoppingList(name:String = "Default") -> DocumentSnapshot?{
let db = Firestore.firestore()
let defaults = UserDefaults.standard
let userId: String! = defaults.string(forKey: "UserUUID")
var doc:DocumentSnapshot?
db.collection("shoppingLists")
.whereField("users." + userId, isEqualTo: true)
.whereField("name", isEqualTo: name)
.limit(to: 1)
.getDocuments() { (querySnapshot, err) in
if let err = err {
print("Error getting documents: \(err)")
} else {
for document in querySnapshot!.documents {
print("\(document.documentID) => \(document.data())")
doc = document
NotificationCenter.default.post(name: NSNotification.Name(rawValue: "DocumentReceived"), object: nil)
break
}
}
}
return doc
}
当通知观察者获得该通知时 - 因此,所需的功能将被自己调用
@objc func loadList(){
//load data here
}
注意 - 不要忘记在不需要时删除添加的观察者
第二个选项 操作完成时加载数据
public class func getProductsInShoppingList(name:String = "Default") -> DocumentSnapshot?{
let db = Firestore.firestore()
let defaults = UserDefaults.standard
let userId: String! = defaults.string(forKey: "UserUUID")
var doc:DocumentSnapshot?
db.collection("shoppingLists")
.whereField("users." + userId, isEqualTo: true)
.whereField("name", isEqualTo: name)
.limit(to: 1)
.getDocuments() { (querySnapshot, err) in
if let err = err {
print("Error getting documents: \(err)")
} else {
for document in querySnapshot!.documents {
print("\(document.documentID) => \(document.data())")
doc = document
DispatchQueue.main.async {
//Load data here
}
break
}
}
}
return doc
}