Mac / iPhone App Development
Home of a Small Time Developer

Adding Reachability Code to your app

Ok so iVersion 1.4 was declined due to not loading correctly when their is no network connectivity.

When the device is connected to a cellular network, iVersion does not load its contents.  After the user enters the URL (http://svn.collab.net/repos/svn/trunk/) and taps “connect,” an error message is received.

Apparently the error message is not clear enough or something, anyway this is not a rant, this is what apple recommends.

Please take a look at the Reachability iPhone program sample which demonstrates the use of the System Configuration Reachability API to detect the absence of WiFi and Wireless Wide Area Network (WWAN) services. Your application can then take appropriate action at the first point where network services are required.

The sample code can be found on Apple developer site, however the two file we are interested in are:

Download the Reachability Code:
Reachability.h

Reachability.m

How to use:
Lets say you have a simple UILabel which you want to update with either “(Offline)” or “(Online)” depending on whether the network is reachable. Your view controller would be defined something like this:

@interface MyStatusView : UIViewController
{
	UILabel * statusLabel;
}
 
@property(nonatomic, assign) IBOutlet UILabel * statusLabel;
 
- (void)reachabilityChanged:(NSNotification *)note;
- (void)updateStatus;
 
@end

Then we add the following code to the view controller .m file:

-(void)viewWillAppear:(BOOL)animated
{
	self.reachability = [Reachability reachabilityWithHostName:@"google.com"];
	[reachability startNotifer];
 
	[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(reachabilityChanged:) name:@"kNetworkReachabilityChangedNotification" object:nil];
 
	[self updateStatus];
}
 
-(void)viewWillDisappear:(BOOL)animated
{
	self.reachability = nil;
	[[NSNotificationCenter defaultCenter] removeObserver:self];
}
 
-(void)reachabilityChanged:(NSNotification*)notification
{
	[self updateStatus];
}
 
-(void)updateStatus
{
	NSLog(@"Reachability changed");
 
	if ([reachability currentReachabilityStatus] == NotReachable)
	{
		statusLabel.text = @"(Offline)";
	}
	else
	{
		statusLabel.text = @"(Online)";
	}
}

I think it’s fairly self explanatory. Basically when the view appears the reachability class is created and started using startNotifier. Then we hook in our reachabilityChanged: method into the notification centre, so it is automatically called when the network status changes. reachabilityChanged: calls updateStatus which simply changes our label depending on the connectivity.

  • Share/Bookmark

Leave a Reply