How to Check For an Active Internet Connection on iOS or Macos

How can I check for an active Internet connection on iOS or macOS?

Important: This check should always be performed asynchronously. The majority of answers below are synchronous so be careful otherwise you'll freeze up your app.



Swift

  1. Install via CocoaPods or Carthage: https://github.com/ashleymills/Reachability.swift

  2. Test reachability via closures

    let reachability = Reachability()!

    reachability.whenReachable = { reachability in
    if reachability.connection == .wifi {
    print("Reachable via WiFi")
    } else {
    print("Reachable via Cellular")
    }
    }

    reachability.whenUnreachable = { _ in
    print("Not reachable")
    }

    do {
    try reachability.startNotifier()
    } catch {
    print("Unable to start notifier")
    }


Objective-C

  1. Add SystemConfiguration framework to the project but don't worry about including it anywhere

  2. Add Tony Million's version of Reachability.h and Reachability.m to the project (found here: https://github.com/tonymillion/Reachability)

  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];
    }

Important Note: The Reachability class is one of the most used classes in projects so you might run into naming conflicts with other projects. 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.

Note: The domain you use doesn't matter. It's just testing for a gateway to any domain.

How can I check for an active Internet connection on iOS or macOS?

Important: This check should always be performed asynchronously. The majority of answers below are synchronous so be careful otherwise you'll freeze up your app.



Swift

  1. Install via CocoaPods or Carthage: https://github.com/ashleymills/Reachability.swift

  2. Test reachability via closures

    let reachability = Reachability()!

    reachability.whenReachable = { reachability in
    if reachability.connection == .wifi {
    print("Reachable via WiFi")
    } else {
    print("Reachable via Cellular")
    }
    }

    reachability.whenUnreachable = { _ in
    print("Not reachable")
    }

    do {
    try reachability.startNotifier()
    } catch {
    print("Unable to start notifier")
    }


Objective-C

  1. Add SystemConfiguration framework to the project but don't worry about including it anywhere

  2. Add Tony Million's version of Reachability.h and Reachability.m to the project (found here: https://github.com/tonymillion/Reachability)

  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];
    }

Important Note: The Reachability class is one of the most used classes in projects so you might run into naming conflicts with other projects. 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.

Note: The domain you use doesn't matter. It's just testing for a gateway to any domain.

Check For Active Internet Connection (Mac App)

You should be able to use the Reachability API for this. See this Apple Guide.

There is also a drop-in replacement on github.

Which is the simplest way to check for Internet connection in iOS?

Take a look at the Reachability Example provided by Apple.

The problem your approach may have is that you could have a timeout and thus, the synchronized download of some data may block your app. As a result Apple may reject your app.

The Reachability Example can be used as follows:

Reachability *_reachability = [Reachability reachabilityForInternetConnection];
NetworkStatus remoteHostStatus = [_reachability currentReachabilityStatus];
if (remoteHostStatus == NotReachable) {
// not reachable
} else if (remoteHostStatus == ReachableViaWiFi) {
// reachable via Wifi
} else if (remoteHostStatus == ReachableViaWWAN) {
// reachable via WWAN
}

iOS: How to test Internet connection in the most easy way, without freezing the app (without Reachability)?

Nayem is right - you should wrap the third option (async network check) in a class method like this:

+ (void)checkInternetConnectivityWithSuccessCompletion:(void (^)(void))completion {

NSOperationQueue *myQueue = [[NSOperationQueue alloc] init];
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] initWithURL:[NSURL URLWithString:@"https://www.google.com"]];
request.timeoutInterval = 10;

[NSURLConnection sendAsynchronousRequest:request queue:myQueue completionHandler:^(NSURLResponse *response, NSData *data, NSError *error)
{
NSHTTPURLResponse *httpResponse = (NSHTTPURLResponse *) response;
NSLog(@"response status code: %ld, error status : %@", (long)[httpResponse statusCode], error.description);

if ((long)[httpResponse statusCode] >= 200 && (long)[httpResponse statusCode]< 400)
{
// do stuff
NSLog(@"Connected!");
completion();
}
else
{
NSLog(@"Not connected!");
}
}];
}

And then call the method like this:

[YourClass checkInternetConnectivityWithSuccessCompletion:^{
// your internet is working - add code here
}];

Detecting internet connectivity continually

Add obeserver like this in Reachability method.

1) [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(reachabilityChanged:) name:kReachabilityChangedNotification object:nil];

It will call automatically when your app open/in background mode and it call reachabilityChanged.

2) [[NSNotificationCenter defaultCenter] postNotificationName:@"ChangeInternetConnection" object:nil];

ChangeInternetConnection you have to add observer to your ViewController to get status when internet changing it's status.

 - (void) checkInternetConnetion {

[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(reachabilityChanged:) name:kReachabilityChangedNotification object:nil];

//NSString *remoteHostName = @"www.apple.com";


self.internetReachability = [Reachability reachabilityForInternetConnection];
[self.internetReachability startNotifier];
[self updateInterfaceWithReachability:self.internetReachability];
}


#pragma mark - Reachability Methods

- (void)updateInterfaceWithReachability:(Reachability *)reachability {
if (reachability == self.internetReachability) {
[self checkStatus:reachability];
}

if (reachability == self.wifiReachability) {
[self checkStatus:reachability];
}
}


-(void)checkStatus :(Reachability *)reachability {

NetworkStatus netStatus = [reachability currentReachabilityStatus];
BOOL connectionRequired = [reachability connectionRequired];
NSString* statusString = @"";

switch (netStatus) {

case NotReachable: {

self.isInternetOn = FALSE;

break;
}

case ReachableViaWWAN: {
self.isInternetOn = TRUE;

break;
}
case ReachableViaWiFi: {
self.isInternetOn = TRUE;

break;
}
}



[[NSNotificationCenter defaultCenter] postNotificationName:@"ChangeInternetConnection" object:nil];

}

- (void) reachabilityChanged:(NSNotification *)note {

Reachability* curReach = [note object];
NSParameterAssert([curReach isKindOfClass:[Reachability class]]);
[self updateInterfaceWithReachability:curReach];
}


Related Topics



Leave a reply



Submit