我已经简化了很多代码,但基本上我正在监听我的单例类“GetUserData”中 firestore 中集合的更改。每当集合中发生更改(添加、删除或修改文档)时,我需要调用视图控制器中的 respondToUserGroupsChanges() 函数。每当集合发生更改时,都会显示打印语句“Collectionchanged”,以便侦听器正常工作。但是 ViewController 中的 respondToUserGroupsChanges() 函数永远不会被调用。我究竟做错了什么?我可以尝试使用一些标志(当有更改时)和 didSet 但我想弄清楚为什么这种方法不起作用,因为我相信我以前已经这样做过。
class GetUserData{
static let shared = GetUserData()
var respondToUserGroupsChanges : (() -> Void)?
func observeUserGroupsChanges(){
db.collection("users").document(currentUserID!).collection("groups").addSnapshotListener { querySnapshot, error in
guard let snapshot = querySnapshot else {
print("Error fetching snapshots: \(error!)")
return
}
print("Collection changed")
self.respondToUserGroupsChanges?()
}
}
class ViewController: UIViewController{
override func viewDidLoad() {
GetUserData.shared.observeUserGroupsChanges()
GetUserData.shared.respondToUserGroupsChanges = self.respondToUserGroupsChanges
}
func respondToUserGroupsChanges(){
print("respond")
}
}
在简化的代码中,您首先调用
observeUserGroupsChanges()
(respondToUserGroupsChanges
将为nil),然后然后将GetUserData.shared.respondToUserGroupsChanges
设置为非零值。
颠倒这两个步骤的顺序:
class ViewController: UIViewController {
override func viewDidLoad() {
//First set GetUserData.shared.respondToUserGroupsChanges to a non-nil value
GetUserData.shared.respondToUserGroupsChanges = self.respondToUserGroupsChanges
//Now when you call observeUserGroupsChanges, `respondToUserGroupsChanges` won't be nil.
GetUserData.shared.observeUserGroupsChanges()
}