Monday 11 May 2015

Detect network change using Reachability in iOS








Following code will help you to detect the change in network availability. Download the reachablity class from here :
  1. #import "Reachability.h"
Then put following code in your App delegate didFinishLaunchingWithOptions method
  1. - (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
  2. {
  3. Reachability *reachability = [Reachability reachabilityForInternetConnection];
  4. [reachability startNotifier];
  5. NetworkStatus status = [reachability currentReachabilityStatus];
  6. if(status == NotReachable)
  7. {
  8. //No internet
  9. }
  10. else if (status == ReachableViaWiFi)
  11. {
  12. //WiFi
  13. }
  14. else if (status == ReachableViaWWAN)
  15. {
  16. //3G
  17. }
  18. [[NSNotificationCenter defaultCenter] postNotificationName:notifcationstr object:status]
  19. }
Set Notification Observer
  1. [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(NetworkreachablityChanging:) name:kReachabilityChangedNotification object:nil];
  2. - (void)NetworkreachablityChanging:(NSNotification *)notification {
  3. Reachability *reachability = (Reachability *)[notification object];
  4. if ([reachability isReachable]) {
  5. NSLog(@"online");
  6. } else {
  7. NSLog(@"offline");
  8. }
  9. }

For such more Blogs you can visit to http://findnerd.com/NerdDigest

No comments:

Post a Comment