3

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
            }

        }
    })
}
KENdi
  • 7,576
  • 2
  • 16
  • 31
  • What exactly is the value suppose to be? Does it ever change during runtime? Is it user specific? If you are using it to check for internet connection it's not a good idea. – JoakimE Jun 04 '17 at 16:55
  • This is expected behavior: it takes a few moments for the Firebase client to connect to its database server, and during this time `.info/connected` will be `false`. Also see https://stackoverflow.com/questions/51187874/detecting-connection-state-called-twice – Frank van Puffelen Jul 05 '18 at 14:06

1 Answers1

3

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.