How to find out if a Wi-Fi is with or without an internet connection

542 views Asked by At

I'd like to find out if a Wi-Fi has internet connection or not. Sometimes our devices are connected with Wi-Fi, but the Wi-Fi doesn't have an internet connection.

NWPathMonitor or Connectivity thirdparty. I tried it, but it is not fool proof.

I know I can write a method to ping a server, but this is a very ineffective and costly affair.

Any ideas?

1

There are 1 answers

6
Paulw11 On

The only way to know for sure if a network has an Internet connection is to try and make a connection to the Internet. There is nothing on the device that you can query to get the answer.

Even if there were it would have to resort to polling/pinging since connectivity can change at any instant.

A WiFi connection can transition from no-Internet to Internet when the user completes a Hotspot login form. A WiFi connection can transition from Internet to no-Internet if the upstream Internet connection fails in some way. A WiFi connection may be connected to the Internet but not be able to communicate with the specific host your app needs due to a routing failure or some other issue.

For all of these reasons Apple actively discourages "pre flight" checks. Even if a check passes a network operation can still fail due to a change in network status that occurred a microsecond later. It is also unnecessary overhead as it is generally a safe assumption that most devices have some sort of Internet connection most of the time, particularly if the device is an iPhone.

You need to handle errors anyway. Just try the operation and see what happens. If there is no network connection it will fail pretty quickly.

If you want to provide more feedback to the user then you could begin actively checking Internet connectivity with exponential back off in response to a connection error.

That way your app isn't constantly "pinging".

You can also use the error to start a process that uses SCNetworkReachability to check connectivity for you. Rather than using that framework directly, particularly if you are writing in Swift, you might like to use something that wraps it and makes it more accessible like Ashley Mills' Reachability.swift