Archive

Posts Tagged ‘IOS Reachability’

How to detect /handle changes in network from 3G to Edge to Wifi in your IOS apps

June 21, 2011 2 comments

The Problem :

You want to detect in your iOS app if the user is on Wifi, 3G or Edge for some reason. Maybe your app downloads large amounts of data or streams media and you want to make sure that the appropriate signal is available for the operation

Also, you would like to detect any changes in the network as well. eg. when your app starts, the user is on wifi, which is awesome for your media rich app, but then he moves into 3G network and you want to take an action based on this change.

The Solution :

Apple has been nice enough to create a complete sample for us. It is called Reachability (Apple link). Here is the gist of it :

in .h file:

// declare Reachability, you no longer have a singleton but manage instances 
Reachability* reachability; 

in .m file:

[[NSNotificationCenter defaultCenter] addObserver:self selector:(handleNetworkChange:) name:kReachabilityChangedNotification object:nil]; 
reachability = [Reachability reachabilityForInternetConnection]; 
[reachability startNotifier]; 
NetworkStatus remoteHostStatus = [reachability currentReachabilityStatus]; 
if(remoteHostStatus == NotReachable) 
{
NSLog(@"no");
} 
else if (remoteHostStatus == ReachableViaWiFiNetwork) 
{
NSLog(@"wifi"); 
} 
else if (remoteHostStatus == ReachableViaCarrierDataNetwork) 
{
NSLog(@"cell"); 
} 
..... 

- (void) handleNetworkChange:(NSNotification *)notice 
{   
NetworkStatus remoteHostStatus = [reachability currentReachabilityStatus];   
if(remoteHostStatus == NotReachable) 
{
NSLog(@"no");
}   
else if (remoteHostStatus == ReachableViaWiFiNetwork) 
{
NSLog(@"wifi"); 
}   
else if (remoteHostStatus == ReachableViaCarrierDataNetwork) 
{
NSLog(@"cell"); 
} 
}