ios - Firebase 查询错误处理

标签 ios swift firebase firebase-realtime-database

我有一些函数可以从 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/

相关文章:

ios - Sierra 更新后无法为 iOS 10 编译

swift - 自定义 iOS 导航栏

swift - 如何将 json 数据发送到 API swift

ios - 我们在此 Google 项目中找不到包 ID '...'

firebase - 数据库触发firebase函数从URL下载图像并将其保存到存储

ios - 如何在 SwiftUI 中更改步进器的背景颜色?

ios - 从 IOS + Swift 将图像上传到 Socket.io 中的服务器

ios - xCode 7 + Swift 2.0 中的编译错误

iOS Swift - 如何获取本地和远程视频的宽高比?

firebase - 如何将身份验证用户链接到 Firestore 中的集合?