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

ID : 865

viewed : 184

Tags : iosmacoscocoacocoa-touchreachabilityios





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

vote vote

100

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.

vote vote

81

I like to keep things simple. The way I do this is:

//Class.h #import "Reachability.h" #import <SystemConfiguration/SystemConfiguration.h>  - (BOOL)connected;  //Class.m - (BOOL)connected {     Reachability *reachability = [Reachability reachabilityForInternetConnection];     NetworkStatus networkStatus = [reachability currentReachabilityStatus];     return networkStatus != NotReachable; } 

Then, I use this whenever I want to see if I have a connection:

if (![self connected]) {     // Not connected } else {     // Connected. Do some Internet stuff } 

This method doesn't wait for changed network statuses in order to do stuff. It just tests the status when you ask it to.

vote vote

72

Using Apple's Reachability code, I created a function that'll check this correctly without you having to include any classes.

Include the SystemConfiguration.framework in your project.

Make some imports:

#import <sys/socket.h> #import <netinet/in.h> #import <SystemConfiguration/SystemConfiguration.h> 

Now just call this function:

/* Connectivity testing code pulled from Apple's Reachability Example: https://developer.apple.com/library/content/samplecode/Reachability  */ +(BOOL)hasConnectivity {     struct sockaddr_in zeroAddress;     bzero(&zeroAddress, sizeof(zeroAddress));     zeroAddress.sin_len = sizeof(zeroAddress);     zeroAddress.sin_family = AF_INET;      SCNetworkReachabilityRef reachability = SCNetworkReachabilityCreateWithAddress(kCFAllocatorDefault, (const struct sockaddr*)&zeroAddress);     if (reachability != NULL) {         //NetworkStatus retVal = NotReachable;         SCNetworkReachabilityFlags flags;         if (SCNetworkReachabilityGetFlags(reachability, &flags)) {             if ((flags & kSCNetworkReachabilityFlagsReachable) == 0)             {                 // If target host is not reachable                 return NO;             }              if ((flags & kSCNetworkReachabilityFlagsConnectionRequired) == 0)             {                 // If target host is reachable and no connection is required                 //  then we'll assume (for now) that your on Wi-Fi                 return YES;             }               if ((((flags & kSCNetworkReachabilityFlagsConnectionOnDemand ) != 0) ||                  (flags & kSCNetworkReachabilityFlagsConnectionOnTraffic) != 0))             {                 // ... and the connection is on-demand (or on-traffic) if the                 //     calling application is using the CFSocketStream or higher APIs.                  if ((flags & kSCNetworkReachabilityFlagsInterventionRequired) == 0)                 {                     // ... and no [user] intervention is needed                     return YES;                 }             }              if ((flags & kSCNetworkReachabilityFlagsIsWWAN) == kSCNetworkReachabilityFlagsIsWWAN)             {                 // ... but WWAN connections are OK if the calling application                 //     is using the CFNetwork (CFSocketStream?) APIs.                 return YES;             }         }     }      return NO; } 

And it's iOS 5 tested for you.

vote vote

65

This used to be the correct answer, but it is now outdated as you should subscribe to notifications for reachability instead. This method checks synchronously:


You can use Apple's Reachability class. It will also allow you to check if Wi-Fi is enabled:

Reachability* reachability = [Reachability sharedReachability]; [reachability setHostName:@"www.example.com"];    // Set your host name here NetworkStatus remoteHostStatus = [reachability remoteHostStatus];  if (remoteHostStatus == NotReachable) { } else if (remoteHostStatus == ReachableViaWiFiNetwork) { } else if (remoteHostStatus == ReachableViaCarrierDataNetwork) { } 

The Reachability class is not shipped with the SDK, but rather a part of this Apple sample application. Just download it, and copy Reachability.h/m to your project. Also, you have to add the SystemConfiguration framework to your project.

vote vote

51

Here's a very simple answer:

NSURL *scriptUrl = [NSURL URLWithString:@"http://www.google.com/m"]; 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 should point to an extremely small website. I use Google's mobile website here, but if I had a reliable web server I'd upload a small file with just one character in it for maximum speed.

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. If you need to know how the user is connected, using Reachability is the way to go.

Careful: This will briefly block your thread while it loads the website. In my case, this wasn't a problem, but you should consider this (credits to Brad for pointing this out).

Top 3 video Explaining How can I check for an active Internet connection on iOS or macOS?







Related QUESTION?