我有一些函数可以从 Firebase 读取数据,但有时我从来没有得到响应(或者它被严重延迟)。我读了here也许 Firebase 可以在接收到数据之前关闭套接字连接。看起来有人有类似的问题here ,但从未发布解决方案。
这是我从 Firebase 下载用户数据的代码示例。
// loads the current user's information
static func loadUserDataWithCompletion(completion: (UserInfo) -> Void) {
let ref = FIRDatabase.database().reference()
print("loading current user data...")
let uid = (FIRAuth.auth()?.currentUser?.uid)!
ref.child("users").queryOrderedByKey().queryEqualToValue(uid).observeEventType(.ChildAdded, withBlock: { (snapshot) in
print("found user data!")
if let dictionary = snapshot.value as? [String:AnyObject] {
let info = userFromDict(dictionary)
// execute code slated for completion
completion(info)
}
})
}
有什么方法可以使用 observeEventType
检测错误?也许那时我至少会得到更多关于问题发生原因的信息。
最佳答案
在观察数据库时,您可能会遇到三种可能的错误:-
- 您还没有定义正确的数据库路径
observe
query - 您正在以错误或错误的方式进行解析
- 您无权在特定时间访问该特定节点(安全规则)
对于前两个你必须自己处理,但对于第三个条件你可以使用 withCancel block :-
FIRDatabase.database().reference().child("users").queryOrderedByKey().queryEqual(toValue: "uid").observe(.childAdded, with: { (snapshot) in
//your code
}, withCancel: {(err) in
print(err) //The cancelBlock will be called if you will no longer receive new events due to no longer having permission.
})
- 就错误处理而言,如果用户在书写时失去网络连接,无论网络延迟或连接如何,您的应用都会保持响应。请参阅Firebase Docs 的离线写入数据 部分
关于ios - Firebase 查询错误处理,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40298763/