我正在尝试运行一个函数,以便能够使用 Firebase 从实时数据库中检索数据,但是每当我运行该函数时;我的函数的 observerSingleEvent 部分不会运行,我已经尝试在其中放置一个打印语句,但它没有运行,也没有将字段读取到变量,任何帮助都是有益的。
func checkIfNewDay() -> Bool {
print(self.currDate)
var ref: FIRDatabaseReference!
ref = FIRDatabase.database().reference()
let userID = FIRAuth.auth()?.currentUser?.uid
print("outside function")
ref.child("user").child(userID!).child("dates").observeSingleEvent(of: .value, with: { (snapshot) in
// Get user value
print("inside function")
let value = snapshot.value as? NSDictionary
print("just to make sure its going inside the function. Delete after")
self.lastDate = value?["lastSaveDate"] as? String ?? "Date Invalid"
self.newLastDate = String(self.lastDate)
if self.newLastDate != "Date Invalid" {
print(self.lastDate)
} else {
print("Error, date not able to be recieved from the database")
self.catchGetDateError = true
self.saveCurrentDate()
}
})
if (!self.catchGetDateError) {
print(self.newLastDate, "newLastDate")
print(self.currentDate, "currentDate")
if (self.newLastDate == self.currentDate) {
print("Day has not moved on.")
return false
} else {
print("Day has moved on!")
return true
}
}
return true
}
对于这么长的函数,我深表歉意——写起来很奇怪。
最佳答案
从评论我想我已经明白了,你想要什么。
要获得像同步这样的结果,您需要实现转义。像这样:
func checkIfNewDay(completion: @escaping (_ isNew: Bool) -> Void) {
print(self.currDate)
var ref: FIRDatabaseReference!
ref = FIRDatabase.database().reference()
let userID = FIRAuth.auth()?.currentUser?.uid
print("outside function")
ref.child("user").child(userID!).child("dates").observeSingleEvent(of: .value, with: { (snapshot) in
// Get user value
print("inside function")
let value = snapshot.value as? NSDictionary
print("just to make sure its going inside the function. Delete after")
self.lastDate = value?["lastSaveDate"] as? String ?? "Date Invalid"
self.newLastDate = String(self.lastDate)
if self.newLastDate != "Date Invalid" {
print(self.lastDate)
if (self.newLastDate == self.currentDate) {
print("Day has not moved on.")
completion(false)
} else {
print("Day has moved on!")
completion(true)
}
} else {
print("Error, date not able to be recieved from the database")
self.catchGetDateError = true
self.saveCurrentDate()
completion(false)
}
})
}
所以,现在你可以使用你的函数了:
checkIfNewDay(completion: { isNew in
// do whatever you want. isNew will have info, that you need.
})
你应该拥有它,因为 .observe 函数是异步工作的。你应该明白这个想法。
希望对您有所帮助。
关于swift - observerSingleEvent 函数未与 Firebase 一起运行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43735790/