Firebase连接状态在首次运行时总是返回false [英] Firebase connection state always returning false on first run

查看:165
本文介绍了Firebase连接状态在首次运行时总是返回false的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在iOS应用中使用以下功能来检查我们是否已连接到Firebase。当这个函数在应用程序中第一次运行时,它总是返回false为连接状态(即使我连接到Firebase)。关闭无互联网警报并再次调用该函数将返回正确的连接状态(true)。



您知道为什么Firebase不会返回 true 第一次运行函数时的连接状态?

  func checkInternetOnLoad(){

let connectedRef = FIRDatabase.database()。reference(withPath:.info / connected)

connectedRef.observeSingleEvent(of:.value,with:{(snapshot)在

//日志快照值(注意:在第一次运行函数时总是为false
print(snapshot.value as?Bool!)

如果let connected = snapshot.value as?Bool {

if!connected {
//我们没有互联网

//显示警报说我们不用没有互联网,按试用重新运行功能,再次检查互联网
let alert = showError(title:你的手机离线,信息:我,cancelMessage:立即尝试,cancelAction:{
self.checkInternetOnLoad()
})
self.present(alert ,animated:true,completion:nil)

} else {

//我们有互联网。做什么
}

}
})
}


<解决方案

解决方案不能解决问题,所以我现在的hacky解决方法是在5秒钟后第二次调用observeSingleEvent()函数,这将返回正确的连接状态。

I use the following function in my iOS app to check if we're connected to Firebase. When this function is run the first time in the app, it always returns false for the connection state (even if I'm connected to Firebase). Dismissing the "no internet" alert and calling the function again returns the correct connection state (true).

Do you know why Firebase doesn't return a true connection state the first time the function is run?

func checkInternetOnLoad(){

    let connectedRef = FIRDatabase.database().reference(withPath: ".info/connected")

    connectedRef.observeSingleEvent(of: .value, with: { (snapshot) in

        // Log snapshot value (Note: this is always false the first time the function is run
        print(snapshot.value as? Bool!)

        if let connected = snapshot.value as? Bool{

            if !connected{
                // We don't have internet

                // Show alert saying we don't have internet. Pressing "Try Now" reruns the function to check internet again.
                let alert = showError(title: "Your Phone's Offline", message: "If you're online and seeing this message, please contact support.", cancelMessage: "Try now", cancelAction: {
                    self.checkInternetOnLoad()
                })
                self.present(alert, animated: true, completion: nil)

            } else {

                // We have internet. Do stuff
            }

        }
    })
}

解决方案

Couldn't figure it out so my hacky workaround for now is to call the observeSingleEvent() function a second time five seconds later, which returns the correct connection state.

这篇关于Firebase连接状态在首次运行时总是返回false的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆