I know this question will appear to be a dupe of many others, however, I don't feel the simple case is well explained here. Coming from an Android and BlackBerry background, making requests through HTTPUrlConnection
instantly fail if there is no connection available. This seems like completely sane behavior, and I was surprised to find NSURLConnection
in iOS did not emulate it.
I understand that Apple (and others who have extended it) provide a Reachability
class to assist with determining the network state. I was happy to first see this and fully expected to see something like bool isNetworkAvailable()
, but instead to my surprise I found a complex system requiring notification registrations and callbacks, and a bunch of seemingly unnecessary details. There must be a better way.
My app already gracefully handles connection failures, including no connectivity. The user is notified of the failure, and the app moves on.
Thus my requirements are simple: Single, synchronous function I can call before all HTTP requests to determine if I should bother actually sending the request or not. Ideally it requires no set up and just returns a boolean.
Is this really not possible on iOS?
Here is a good solution for checking connectivity using Swift, without using Reachability. I found it on this blog.
Create a new Swift file in your project called
Network.swift
(for example). Paste this code inside that file:You can then check for connectivity anywhere in your project by using:
Seeing as this thread is the top google result for this type of question, I figured I would provide the solution that worked for me. I was already using AFNetworking, but searching didn't reveal how to accomplish this task with AFNetworking until midway through my project.
What you want is the AFNetworkingReachabilityManager.
You can also use the following to test reachability synchronously (once monitoring has started):
Someone has solved this in a simple, reusable way before.
DDGReachability
.EDIT: Or
tonymillion/Reachability
.I extracted the code and put into one single method, hope it would help others.
...
I think this could help..
It is possible and it is really simple if you look at it when finishing the implementation, which is again - very simple, since the only items you need are two boolean variables: internet reachability and host reachability (you often need more than one of these). Once you assemble your helper class that can determine the connections status, you really don't care again of the implementation needed for knowing these procedures.
Example:
And the .m file: