I have recently been working on a new iOS app for the iPhone and I ran into a couple of issues. I don’t really have time to go over them all in this post, but I did want to document one of them because I hear it can be a big deal as far as getting your app approved by Apple. The issue is that of making sure you handle things gracefully if the user’s phone is unable to connect to the internet and they try to do something that does require a connection.
The way I decided to handle it was to use the reachability collection provided by apple. I downloaded the reachability sample from Apple and then copied and imported the 4 files from the “classes” directory into my project.
Then I added the “SystemConfiguration.framework” to my project.
Now I have all of the prereqs for my solution. The next thing I did was I created a NetworkReachabilityTest class with NSObject as its base class. I added a single method called “isNetworkReachableWithAlert” that returned a bool and included one parameter. The parameter specified whether it should automatically pop up an alert box in case of a lack of network connectivity.
I chose to do it this way (as a dumb small class) so I didn’t have to copy the code for this method into every page. Plus it gives me the flexibility to easily reuse it in future projects. So now, before I do something that requires network connectivity I instantiate an instance of this class, I do the check, and if the connection is there I do the work. If the connection is not there I can bail out instead.
Here’s the code (some of this code was included in the example and some was found here around post 29 or 30:
Reachability *r = [Reachability reachabilityWithHostName:@”www.signandtrade.com”];
NetworkStatus internetStatus = [r currentReachabilityStatus];
if ((internetStatus != ReachableViaWiFi) && (internetStatus != ReachableViaWWAN))
UIAlertView *myAlert = [[UIAlertView alloc] initWithTitle:@”No Internet Connection” message:@”An internet connection via WiFi or cellular network is required for this portion of the app to work.” delegate:self cancelButtonTitle:@”Ok” otherButtonTitles:nil];
That’s in the implementation file of my simple class and it is basically the only thing there! And it does everything we need.
And here it is in use:
NetworkReachabilityTest *nrt = [[NetworkReachabilityTest alloc] init];
if ([nrt isNetworkReachableWithAlert:YES])
// logic that requires or includes web activity here
Hope that helps. Hope it makes sense. Better ideas or improvements on it are welcome, I just wanted to give someone a simple example of something that I know works along with the steps I took to make it work.