Firebase connection state always returns false on first launch

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

Do you know why Firebase doesn't return connection status true

when you first run the function?

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

        }
    })
}

      

+3


source to share


1 answer


Couldn't figure it out, so now I have cracked a workaround to call the observSingleEvent () function a second time after five seconds, which returns the correct connection state.



+1


source







All Articles