首页 > 解决方案 > ObsetveSingleEvent 错误处理

问题描述

userRef.child(userId).observeSingleEvent(of: .value, with: { snapshot in
        //some codes
})

这是我从 firebase 数据库中获取一些用户数据的代码。我的问题是如果出现错误(如网络错误、请求超时、未知错误)如何获取错误?与其他事件(setValue、updateValue 等)相比,observeSingleEvent 没有完成块

我也试过:

userRef.child(userId).observeSingleEvent(of: .value, with: {(snapshot) in
    // print something
} , withCancel: {(error) in
    // print something
})

仍然不会与取消一起进入。

标签: iosswiftfirebasefirebase-realtime-database

解决方案


这是你想要的?

userRef.child(userId).observeSingleEvent(of: .value, with: { (snapshot) in
        print("Worked")           
    }) { (error) in
        print("Didn't")        
    }

如果您在观察中犯了错误,您还可以再次检查。

if snapshot.value is NSNull{
     //snapshot is null
} else{
     //Not null
}

推荐阅读