Tuesday 13 March 2012

Monitor Network Status and Network Type in iOS


Hi All,

In most of the iOS application which uses server and server api's wants to a check whether network is available at any moment when application runs.
we all know how to check the network status (Using Apple's Reachability code we can check the network status by pinging to a hosted server).
But some cases instead of checking for network is available we need to get/alert about network status change and the network type change.

So here I got up with an implementation of a custom class that will alert the network status change.


//To get the Network Status/ Change in Network Type with NSNetworkMonitor,
(Here prefix NS means not 'Next Step' it just 'Naveen Shan' my name, if you don't like change it.)

1. Initialize the Network Monitor on App Launch.

 //for monitoring network connectivity  
 [NSNetworkMonitor initializeNetworkMonitor];  

2. To Catch the Network Status implement the following Notification.

 //to catch network status.  
 [[NSNotificationCenter defaultCenter] addObserver:self  
                      selector:@selector(changeInNetworkConnection:)  
                        name:KNETWORKNOTIFIER  
                       object:nil];  

3. The Response Method is implemented as follows,

 -(void)changeInNetworkConnection:(NSNotification *)notification {  
   NSDictionary *status = [notification object];  
   if ([[status objectForKey:@"NetworkAvailable"] boolValue]) {  
     NSLog(@"The NetworkConnection StatusDidChanged : NO Connection");  
   }  
   else  {  
     if ([[status objectForKey:@"NetworkType"] isEqualToString:@"WiFi"]) {  
       NSLog(@"The NetworkConnection StatusDidChanged : wifi Connection");  
     }  
     else  {  
       NSLog(@"The NetworkConnection StatusDidChanged : wann Connection");  
     }  
   }  
 }  

Some Helper Methods

 +(BOOL)isNetWorkConnectionAvailable;  
 +(NetworkAvailable)currentNetwork;  

One Important Tip

- we get a network change notification on app launch when the network status is changed while app is in minimize stage.

Dependencies

- Need to add Apple's Reachability Classes.
- Need to add SystemConfiguration.framework.

I attached Complete code here

if you need more details feel free to contact me

thanks,
Naveen Shan

No comments:

Post a Comment