侦听实时数据库中更改的孩子的正确方法是什么?
这是我的尝试,但是当我从Web控制台手动更新billingUpdated(Int)的值时,什么都不会打印。
let userID = Auth.auth().currentUser?.uid as! String
let ref = Database.database().reference()
override func viewDidLoad() {
super.viewDidLoad()
self.ref.child("users").child(userID).child("billingUpdated").observe(.childChanged, with: { (snapshot) in
print("child changed")
})
}
答案 0 :(得分:0)
与此有关的所有文档和教程都已与swift的最新版本一起过时了〜看起来很简单,但是无论我如何编写代码,它都行不通。
我从未找到答案,但这是我的解决方法。如果您知道答案,请告诉我。
解决方法:循环watchSingleEvent直到更改值。
在viewDidLoad下:waitForChange()
功能:
func waitForChange() {
self.ref.child("users").child(self.userID).child("billingUpdated").observeSingleEvent(of: .value) { (snapshot) in
let billingUpdated = snapshot.value as! Int
if billingUpdated == 0 {
DispatchQueue.main.asyncAfter(deadline: .now() + 2.0) {
print("looping again")
self.waitForChange()
}
}
else{
print("value has been updated")
}
}
}
我添加了DispatchQueue.main.asyncAfter
,因此循环不会每秒运行100次。