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

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

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"); 
} 
} 
Advertisements
  1. February 6, 2013 at 2:05 pm

    “How to detect /handle changes in network from 3G
    to Edge to Wifi in your IOS apps IOS Tips and Tricks from a developer” was indeed a quite good
    blog, . Continue authoring and I’m going to keep on browsing! Thanks for your time ,Caroline

  1. February 23, 2013 at 3:39 pm

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: