【发布时间】:2017-10-21 13:43:36
【问题描述】:
我在我的 iOS 应用中使用以下函数来检查我们是否已连接到 Firebase。当这个函数在应用程序中第一次运行时,它总是返回 false 的连接状态(即使我连接到 Firebase)。关闭“无互联网”警报并再次调用该函数会返回正确的连接状态 (true)。
你知道为什么 Firebase 在函数第一次运行时不返回true 连接状态吗?
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
}
}
})
}
【问题讨论】:
-
该值究竟是什么?它在运行时会改变吗?它是用户特定的吗?如果您使用它来检查互联网连接,这不是一个好主意。
-
这是预期行为:Firebase 客户端连接到其数据库服务器需要一些时间,在此期间
.info/connected将是false。另见stackoverflow.com/questions/51187874/…
标签: swift xcode firebase firebase-realtime-database