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
}
}
})
}