菜单

Check if Active Internet Connection Exists on iOS Device

2014年10月30日 - iOS

There may be a plethora of reasons that you need to check whether or not the device that is using your application has an internet connection.
I have listed two methods here. A quicky use a pre built class method or the do it yourself I like getting dirty with code method. Both ways are valid.

At the bottom there is also another solution posted by a StackOverflow member.

Method 1
You can use a simple (ARC and GCD compatible) class to do it for you.

1) Add SystemConfiguration framework to the project but don’t worry about including it anywhere

2) Add T.Million’s version of Reachability.h and Reachability.m to the project, get these files from the option below:

This content is locked!
Please support us, use one of the buttons below to unlock the content.
tweet

like us

+1 us

3) Update the interface section:

#import "Reachability.h"

// Add this to the interface in the .m file of your view controller
@interface MyViewController ()
{
    Reachability *internetReachableFoo;
}
@end

4) Then implement this method in the .m file of your view controller which you can call:

// Checks if we have an internet connection or not
- (void)testInternetConnection
{   
    internetReachableFoo = [Reachability reachabilityWithHostname:@"www.google.com"];

    // Internet is reachable
    internetReachableFoo.reachableBlock = ^(Reachability*reach)
    {
        // Update the UI on the main thread
        dispatch_async(dispatch_get_main_queue(), ^{
            NSLog(@"Yayyy, we have the interwebs!");
        });
    };

    // Internet is not reachable
    internetReachableFoo.unreachableBlock = ^(Reachability*reach)
    {
        // Update the UI on the main thread
        dispatch_async(dispatch_get_main_queue(), ^{
            NSLog(@"Someone broke the internet :(");
        });
    };

    [internetReachableFoo startNotifier];
}

Method 2
For those of you who like to Do it yourself the old way you can use Apple’s outdated Reachability class.

1) Add SystemConfiguration framework to the project but don’t worry about including it anywhere

2) Add Apple’s version of Reachability.h and Reachability.m to the project (Download )

3) Add @class Reachability; to the .h file of where you are implementing the code

4) Create a couple instances to check in the interface section of the .h file:

3) Add @class Reachability; to the .h file of where you are implementing the code

4) Create a couple instances to check in the interface section of the .h file:

Reachability* internetReachable;
Reachability* hostReachable;

5) Add a method in the .h for when the network status updates:

1
-(void) checkNetworkStatus:(NSNotification *)notice;

6) Add #import “Reachability.h” to the .m file where you are implementing the check

7) In the .m file of where you are implementing the check, you can place this in one of the first methods called (init or viewWillAppear or viewDidLoad etc):

-(void) viewWillAppear:(BOOL)animated
{
    // check for internet connection
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(checkNetworkStatus:) name:kReachabilityChangedNotification object:nil];

    internetReachable = [Reachability reachabilityForInternetConnection];
    [internetReachable startNotifier];

    // check if a pathway to a random host exists
    hostReachable = [Reachability reachabilityWithHostName:@"www.apple.com"];
    [hostReachable startNotifier];

    // now patiently wait for the notification
}

8) Set up the method for when the notification gets sent and set whatever checks or call whatever methods you may have set up (in my case, I just set a BOOL)

-(void) checkNetworkStatus:(NSNotification *)notice
{
    // called after network status changes
    NetworkStatus internetStatus = [internetReachable currentReachabilityStatus];
    switch (internetStatus)
    {
        case NotReachable:
        {
            NSLog(@"The internet is down.");
            self.internetActive = NO;

            break;
        }
        case ReachableViaWiFi:
        {
            NSLog(@"The internet is working via WIFI.");
            self.internetActive = YES;

            break;
        }
        case ReachableViaWWAN:
        {
            NSLog(@"The internet is working via WWAN.");
            self.internetActive = YES;

            break;
        }
    }

    NetworkStatus hostStatus = [hostReachable currentReachabilityStatus];
    switch (hostStatus)
    {
        case NotReachable:
        {
            NSLog(@"A gateway to the host server is down.");
            self.hostActive = NO;

            break;
        }
        case ReachableViaWiFi:
        {
            NSLog(@"A gateway to the host server is working via WIFI.");
            self.hostActive = YES;

            break;
        }
        case ReachableViaWWAN:
        {
            NSLog(@"A gateway to the host server is working via WWAN.");
            self.hostActive = YES;

            break;
        }
    }
}

9) In your dealloc or viewWillDisappear or similar method, remove yourself as an observer

-(void) viewWillDisappear:(BOOL)animated
{
    [[NSNotificationCenter defaultCenter] removeObserver:self];
}

Note: There might be an instance using viewWillDisappear where you receive a memory warning and the observer never gets unregistered so you should account for that as well. The domain you use doesn’t matter. It’s just testing for a gateway to any domain.

Important Note: The Reachability class is one of the most used classes in projects so you might run into naming conflicts with other projects like ShareKit. If this happens, you’ll have to rename one of the pairs of Reachability.h and Reachability.m files to something else to resolve the issue.

Method 3
StackOverflow member: Erik posted this solution:

NSURL *scriptUrl = [NSURL URLWithString:@"http://apps.wegenerlabs.com/hi.html"];
NSData *data = [NSData dataWithContentsOfURL:scriptUrl];
if (data)
    NSLog(@"Device is connected to the internet");
else
    NSLog(@"Device is not connected to the internet");

“The URL points to an extremely small website that can be loaded fast in a cellular network. You are welcome to use my website, but you can also put a small file on your own website.

If checking whether the device is somehow connected to the internet is everything you want to do, I’d definitely recommend using this simple solution.” @Erik

Whilst this is not as flexible as the Reachability variants, this method is often easier to handle.

There you go. You should now be able to successfully check whether the device that is running your iOS application has an internet connection or not. Should you have any comments or ideas please leave them below.

发表评论

电子邮件地址不会被公开。 必填项已用*标注