Checking if an iOS app is online (Reachability)

Guides | Tutorial By 5 years ago

When developing any software it’s important to make sure everything flows smoothly. This can be tougher when it comes to network connections as they’re unreliable, especially on a mobile device where the connection can drop out frequently or can be extremely slow (if you’re using 3G).

Aside from just chucking up an error message if there’s a problem, good usability starts before you ever make your network connection. Using Apple’s reachability class lets you easily see when your iOS device connects or disconnects from the net. You can also tell whether it’s Wifi you’re connected to or 3G, good for not downloading too much and eating up all the user’s cellular data.

To do this, first download Apple’s Reachability class. Include the Reachability.h and Reachability.m files in your project. Import the Reachability.h header into your desired file, then link your project with the SystemConfiguration.framework.

Now create a Reachability object. There are four different types, one for checking any internet connection, one for any wifi connection, and two for a connection between a host or IP address. In this example I will do any internet connection (probably the most common).

Reachability* reachability = [[Reachability reachabilityForInternetConnection] retain];
[reachability startNotifier];

Now to determine when it has changed, register an NSNotification observer

[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(reachabilityChanged:) name:kReachabilityChangedNotification object:nil];

Finally implement the notification method

- (void) reachabilityChanged:(NSNotification*) notification
	Reachability* reachability = notification.object;

	if(reachability.currentReachabilityStatus == NotReachable)
		NSLog(@"Internet off");
		NSLog(@"Internet on");

The Reachability object lets you check the system’s internet status through the currentReachabilityStatus property. There are three possibilities.

NotReachable: Obviously, there’s no internet connection
ReachableViaWiFi: Wifi connection
ReachableViaWWAN: 3G or 4G connection

My most common use of the Reachability class is if a user tries to load a results page or something similar while their offline, if they come back online on the same page I then perform the network request on their behalf (rather than having them go back to manually resubmit).