Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Easiest way to determine whether iPhone internet connection is available?

Tags:

iphone

I am looking to determine whether an internet connection is available on the iPhone. It doesn't matter for the app whether it's wifi or EDGE or whatever.

Using the code from the SeismicXML example doesn't seem to work and the Reachability example code from Apple seems like overkill for the app...

Is there a quick and easy way to determine network availability on the iPhone?

Thanks, Ben

like image 517
user21293 Avatar asked Apr 24 '09 05:04

user21293


2 Answers

Follow following 3 easy steps -

Step 1: Include "SystemConfiguration.framework" framework in your project

Step 2: Included Apple's Reachability.h and Reachability.m from Reachability example

Step 3: Now add this code anywhere in your .m.

Reachability* wifiReach = [[Reachability reachabilityWithHostName: @"www.apple.com"] retain];
NetworkStatus netStatus = [wifiReach currentReachabilityStatus];

switch (netStatus)
{
    case NotReachable:
    {
        NSLog(@"Access Not Available");
        break;
    }

    case ReachableViaWWAN:
    {
        NSLog(@"Reachable WWAN");
        break;
    }
    case ReachableViaWiFi:
    {
        NSLog(@"Reachable WiFi");
        break;
    }
}
like image 58
SoHeL Avatar answered Oct 16 '22 22:10

SoHeL


I included Apple's Reachability.h & .m from their Reachability example, plus the SystemConfiguration framework mentioned above, and then added the following code to my app, which has two advantages over the above answer - it gives you more information, and you get asynchronous notifications of network status changes.

In your app delegate, or similar, add this when you start up:

[self startReachability];

Then add this method, which gets called when the network changes:

#pragma mark Reachability changed
- (void)reachabilityChanged:(NSNotification*)aNote
{
self.remoteHostStatus = [[Reachability sharedReachability] remoteHostStatus];

switch (self.remoteHostStatus)
{
case NotReachable:
  debugForComponent(kDebugMaskApp,@"Status changed - host not reachable");
  break;

case ReachableViaCarrierDataNetwork:
  debugForComponent(kDebugMaskApp,@"Status changed - host reachable via carrier");
  break;

case ReachableViaWiFiNetwork:
  debugForComponent(kDebugMaskApp,@"Status changed - host reachable via wifi");     
  break;

default:
  debugForComponent(kDebugMaskApp,@"Status changed - some new network status");
  break;
}
}
like image 35
Jane Sales Avatar answered Oct 16 '22 22:10

Jane Sales