您好, 欢迎来到 !    登录 | 注册 | | 设为首页 | 收藏本站

从Firebase数据库异步方法返回值

从Firebase数据库异步方法返回值

您必须自己使用异步完成处理程序,并验证是否存在Internet连接:

func checkUsernameAlreadyTaken(username: String, completionHandler: (Bool) -> ()) {
    databaseRef.child("usernames").child("\(username)").observe(.value, with: { (snapshot) in
        print(username)
        if snapshot.exists() {
            completionHandler(false)
        } else {
            let connectedRef = FIRDatabase.database().reference(withPath: ".info/connected")
            connectedRef.observe(.value, with: { snapshot in
                if let connected = snapshot.value as? Bool, connected {
                    completionHandler(true)
                } else {
                    completionHandler(false)
                    // Show a popup with the description
                    let alert = UIAlertController(title: NSLocalizedString("No connection", comment: "Title Internet connection error"), message: NSLocalizedString("No internet connection, please go online", comment: "Internet connection error saving/retriving data in Firebase Database"), preferredStyle: .alert)
                    let defaultOkAction = UIAlertAction(title: NSLocalizedString("No internet connection, please go online", comment: "Internet connection error saving/retriving data in Firebase Database"), style: .default, handler: nil)
                    alert.addAction(defaultOkAction)

                    self.present(alert, animated: true, completion: nil)
                }
            })
        }
    })
}

然后,使用以下命令调用方法

checkIfUserExists(username: text, completionHandler: { (value) in
    // ...
})
其他 2022/1/1 18:15:05 有498人围观

撰写回答


你尚未登录,登录后可以

和开发者交流问题的细节

关注并接收问题和回答的更新提醒

参与内容的编辑和改进,让解决方法与时俱进

请先登录

推荐问题


联系我
置顶