iosswiftfirebasereachability

Firebase -can Database.database().reference(withPath: ".info/connected") substitute for Ashley Mills Reachability


I was in a situation where the router with the wifi was plugged in but the router wasn't connected to the internet (no wifi). Whatever reachability class I was using at the time thought it was connected because wifi was available but it couldn't determine that the wifi itself couldn't get a connection.

I now use Ashley Mills Reachability and it works fine because it can tell wether I'm connected to the internet or not by pinging a host name.

let reachability = Reachability(hostname: "www.google.com")

reachability.whenReachable = { (reachability) in

    // connection is fine remove no connection alert if it's on screen
}
reachability.whenUnreachable = { (reachability) in

    // can't ping Google so alert no connection
}

Firebase has similar feature:

let connectedRef = Database.database().reference(withPath: ".info/connected")
connectedRef.observe(.value, with: { (connected) in

    if let boolean = connected.value as? Bool, boolean == true {

          // connection is fine remove no connection alert if it's on screen
     else {

          // can't ping Firebase so alert no connection
     }
})

The question is can the above Firebase feature tell if my wifi is on (router plugged in) but the wifi itself is not connected to the internet (no wifi) like AshleyMills does?


Solution

  • Really late to the party, but I can confirm the Firebase feature does in fact work properly. It checks for connection to the Firebase Database. So, if your wifi is on but no internet, then Firebase will say there's no internet.

    It's remarkably simple. You are testing a connection to Firebase. If it can't reach Firebase, it doesn't matter if there's wifi or cell data or anything else. If it can't reach it, it can't reach it, and it will tell you there's no connection.

    Hope that helps someone in the future. Oh, and I've been using this code in my production app for over a year.