Breaking News
Home / iOS / iOS Snippets / How to check if network is Reachable in iOS?

How to check if network is Reachable in iOS?

Snippet

Any good mobile application would keep a track or aleast check whether the network is reachable or not as the iPhone may have a bad reception, the wifi may not be connected etc. This is also a requirement by Apple for application submission that the application must implement and check for Reachability so that the apps don’t crash or hang while performing a network related operation. This helps ensure a good application experience.

  1. (BOOL) connectedToNetwork
  2. {
  3.     // Create zero addy
  4.     struct sockaddr_in zeroAddress;
  5.     bzero(&zeroAddress, sizeof(zeroAddress));
  6.     zeroAddress.sin_len = sizeof(zeroAddress);
  7.     zeroAddress.sin_family = AF_INET;
  8.        
  9.     // Recover reachability flags
  10.     SCNetworkReachabilityRef defaultRouteReachability = SCNetworkReachabilityCreateWithAddress(NULL, (struct sockaddr *)&zeroAddress);
  11.     SCNetworkReachabilityFlags flags;
  12.        
  13.     BOOL didRetrieveFlags = SCNetworkReachabilityGetFlags(defaultRouteReachability, &flags);
  14.     CFRelease(defaultRouteReachability);
  15.        
  16.     if (!didRetrieveFlags)
  17.     {
  18.         NSLog(@"Error. Could not recover network reachability flags");
  19.         return NO;
  20.     }
  21.        
  22.     BOOL isReachable = flags & kSCNetworkFlagsReachable;
  23.     BOOL needsConnection = flags & kSCNetworkFlagsConnectionRequired;
  24.         BOOL nonWiFi = flags & kSCNetworkReachabilityFlagsTransientConnection;
  25.        
  26.         NSURL *testURL = [NSURL URLWithString:@"http://www.apple.com/"];
  27.         NSURLRequest *testRequest = [NSURLRequest requestWithURL:testURL  cachePolicy:NSURLRequestReloadIgnoringLocalCacheData timeoutInterval:20.0];
  28.         NSURLConnection *testConnection = [[NSURLConnection alloc] initWithRequest:testRequest delegate:self];
  29.        
  30.     return ((isReachable && !needsConnection) || nonWiFi) ? (testConnection ? YES : NO) : NO;
  31. }

<!>

[pb_builder]

Check Also

EKCalendar – That account does not allow calendars to be added or removed

Usecase When I am trying to create a new Calendar programmatically using the EventKit API …

Advertisment ad adsense adlogger