If you like my tutorials, you will love my book . It is chockful of advanced programming techniques and the only comprehensive barcode reference for serious iOS developers.
Our DNA is written in Objective-C

Detecting Internet Connectivity

For the latest version of GeoCorder Apple required me to show an alert if there was not internet connection. This is meant to prevent “user confusion” which would occur if the user is expecting something to happen staring at his screen, but nothing happens because of lack of data connectivity.

There is a good example from which you can steal the technique, but it took me some experimenting to find the right mix. For some reason that escapes me the regular connectivity check would only work within the sample, but not in my own code.

First you need to add Reachability.h and .m from the sample project to your own project. Then you need to add the existing SystemConfiguration.framework to your frameworks. Finally the code below does the check against a server you specify and shows an alert if there is no connectivity.

After app launch you need to set a host name for the check:

[[Reachability sharedReachability] setHostName:@""];

And then at the place where you want the check itself to be executed:

- (void)viewDidAppear:(BOOL)animated
	NetworkStatus internetStatus = [[Reachability sharedReachability] remoteHostStatus];
	if ((internetStatus != ReachableViaWiFiNetwork) && (internetStatus != ReachableViaCarrierDataNetwork))
		UIAlertView *myAlert = [[UIAlertView alloc] initWithTitle:@"No Internet Connection" message:@"You require an internet connection via WiFi or cellular network for location finding to work." delegate:self cancelButtonTitle:@"Ok" otherButtonTitles:nil];
		[myAlert show];
		[myAlert release];

This seems to do the trick nicely. Copy&Paste it as needed into your own code, so that your poor users will never again be “confused”.

Categories: Recipes

%d bloggers like this: