我使用firebase执行查询,以检查是否有任何具有特定值的子对象。问题是如果没有这样的对象代码不运行。因此,在下面的代码中,如果没有具有facebookID
的子项为17
的对象,则其余代码将永远不会运行。有没有办法确定查询何时找到0
结果?
func previousUser(completion:(result:Bool)->Void){
var queryFound = false
print("check if user is previous")
print(UserData.globalfacebookID)
let ref = Firebase(url:"https://amber-torch-556.firebaseio.com/Users")
ref.queryOrderedByChild("facebookID").queryEqualToValue(17).observeSingleEventOfType(.ChildAdded, withBlock: { snapshot in
print(snapshot.childrenCount)
print("query has ran")
UserData.globalparseID = snapshot.key
queryFound = true
completion(result:queryFound)
})
答案 0 :(得分:1)
检查你的参考以确保它有效。
并试试这个
ref.queryOrderedByChild("facebookID").queryEqualToValue(17)
.observeEventType(.Value, withBlock: { snapshot in
if snapshot.value is NSNull {
print("dude, snapshot was null")
} else {
print(snapshot.key)
}
})
将.ChildAdded更改为.Value,然后检查NSNull
答案 1 :(得分:0)
要检查查询是否返回0结果,您可以按如下方式检查快照:
if snapshot.exists() {
// write relevant logic here
}
else {
// handle the case when a query finds 0 results
}
在你的情况下,
func previousUser(completion:(result:Bool)->Void){
var queryFound = false
print("check if user is previous")
print(UserData.globalfacebookID)
let ref = Firebase(url:"https://amber-torch-556.firebaseio.com/Users")
ref.queryOrderedByChild("facebookID").queryEqualToValue(17).observeSingleEventOfType(.ChildAdded, withBlock: { snapshot in
if snapshot.exists() {
print(snapshot.childrenCount)
print("query has ran")
UserData.globalparseID = snapshot.key
queryFound = true
completion(result:queryFound)
}
else {
// handle the case where query finds zero(0) results
}
})
希望这有帮助!