By Brock Woolf


2009-07-05 08:45:01 8 Comments

I would like to check to see if I have an Internet connection on iOS using the Cocoa Touch libraries or on macOS using the Cocoa libraries.

I came up with a way to do this using an NSURL. The way I did it seems a bit unreliable (because even Google could one day be down and relying on a third party seems bad), and while I could check to see for a response from some other websites if Google didn't respond, it does seem wasteful and an unnecessary overhead on my application.

- (BOOL) connectedToInternet
{
    NSString *URLString = [NSString stringWithContentsOfURL:[NSURL URLWithString:@"http://www.google.com"]];
    return ( URLString != NULL ) ? YES : NO;
}

Is what I have done bad, (not to mention stringWithContentsOfURL is deprecated in iOS 3.0 and macOS 10.4) and if so, what is a better way to accomplish this?

30 comments

@Prakhar Prakash Bhardwaj 2019-03-21 18:52:24

For my iOS Projects, I recommend using

Reachability Class

Declared in Swift. For me, it works simply fine with

Wi-Fi and Cellular data

.

 import SystemConfiguration

 public class Reachability {

 class func isConnectedToNetwork() -> Bool {

    var zeroAddress = sockaddr_in(sin_len: 0, sin_family: 0, sin_port: 0, sin_addr: in_addr(s_addr: 0), sin_zero: (0, 0, 0, 0, 0, 0, 0, 0))
    zeroAddress.sin_len = UInt8(MemoryLayout.size(ofValue: zeroAddress))
    zeroAddress.sin_family = sa_family_t(AF_INET)

    let defaultRouteReachability = withUnsafePointer(to: &zeroAddress) {
        $0.withMemoryRebound(to: sockaddr.self, capacity: 1) {zeroSockAddress in
            SCNetworkReachabilityCreateWithAddress(nil, zeroSockAddress)
        }
    }

    var flags: SCNetworkReachabilityFlags = SCNetworkReachabilityFlags(rawValue: 0)
    if SCNetworkReachabilityGetFlags(defaultRouteReachability!, &flags) == false {
        return false
    }

    let isReachable = (flags.rawValue & UInt32(kSCNetworkFlagsReachable)) != 0
    let needsConnection = (flags.rawValue & UInt32(kSCNetworkFlagsConnectionRequired)) != 0
    let ret = (isReachable && !needsConnection)
    return ret
} }

Use conditional statement,

if Reachability.isConnectedToNetwork(){
          * Enter Your Code Here*
        }
    }
    else{
        print("NO Internet connection")
    }

This class is useful in almost every case your app uses the Internet Connection. Such as if the condition is true, API can be called or task could be performed.

@nuynait 2018-04-02 16:45:28

Alamofire

I know the question is asking for Coca Touch solution, but I want to provide a solution for people who searched check internet connection on iOS and will have one more option here.

If you are already using Alamofire, here is what you can benifit from that.

You can add following class to your app, and call MNNetworkUtils.main.isConnected() to get a boolean on whether its connected or not.

#import Alamofire

class MNNetworkUtils {
  static let main = MNNetworkUtils()
  init() {
    manager = NetworkReachabilityManager(host: "google.com")
    listenForReachability()
  }

  private let manager: NetworkReachabilityManager?
  private var reachable: Bool = false
  private func listenForReachability() {
    self.manager?.listener = { [unowned self] status in
      switch status {
      case .notReachable:
        self.reachable = false
      case .reachable(_), .unknown:
        self.reachable = true
      }
    }
    self.manager?.startListening()
  }

  func isConnected() -> Bool {
    return reachable
  }
}

This is a singleton class. Every time, when user connect or disconnect the network, it will override self.reachable to true/false correctly, because we start listening for the NetworkReachabilityManager on singleton initialization.

Also in order to monitor reachability, you need to provide a host, currently I am using google.com feel free to change to any other hosts or one of yours if needed. Change the class name and file name to anything matching your project.

@PersianBlue 2019-03-18 10:16:10

Please can you help with the usage of the above code. How to use it ?

@nuynait 2019-03-18 14:34:22

@PersianBlue You can add following class to your app, and call MNNetworkUtils.main.isConnected() to get a boolean on whether its connected or not. (This is already mentioned in the answer)

@PersianBlue 2019-03-19 06:29:10

Yes i had already tried that but it always gives me false no matter what the state of internet is.

@klcjr89 2012-11-30 03:26:10

Here is how I do it in my apps: While a 200 status response code doesn't guarantee anything, it is stable enough for me. This doesn't require as much loading as the NSData answers posted here, as mine just checks the HEAD response.

Swift Code

func checkInternet(flag:Bool, completionHandler:(internet:Bool) -> Void)
{
    UIApplication.sharedApplication().networkActivityIndicatorVisible = true

    let url = NSURL(string: "http://www.google.com/")
    let request = NSMutableURLRequest(URL: url!)

    request.HTTPMethod = "HEAD"
    request.cachePolicy = NSURLRequestCachePolicy.ReloadIgnoringLocalAndRemoteCacheData
    request.timeoutInterval = 10.0

    NSURLConnection.sendAsynchronousRequest(request, queue:NSOperationQueue.mainQueue(), completionHandler:
    {(response: NSURLResponse!, data: NSData!, error: NSError!) -> Void in

        UIApplication.sharedApplication().networkActivityIndicatorVisible = false

        let rsp = response as! NSHTTPURLResponse?

        completionHandler(internet:rsp?.statusCode == 200)
    })
}

func yourMethod()
{
    self.checkInternet(false, completionHandler:
    {(internet:Bool) -> Void in

        if (internet)
        {
            // "Internet" aka Google URL reachable
        }
        else
        {
            // No "Internet" aka Google URL un-reachable
        }
    })
}

Objective-C Code

typedef void(^connection)(BOOL);

- (void)checkInternet:(connection)block
{
    NSURL *url = [NSURL URLWithString:@"http://www.google.com/"];
    NSMutableURLRequest *headRequest = [NSMutableURLRequest requestWithURL:url];
    headRequest.HTTPMethod = @"HEAD";

    NSURLSessionConfiguration *defaultConfigObject = [NSURLSessionConfiguration ephemeralSessionConfiguration];
    defaultConfigObject.timeoutIntervalForResource = 10.0;
    defaultConfigObject.requestCachePolicy = NSURLRequestReloadIgnoringLocalAndRemoteCacheData;

    NSURLSession *defaultSession = [NSURLSession sessionWithConfiguration:defaultConfigObject delegate:self delegateQueue: [NSOperationQueue mainQueue]];

    NSURLSessionDataTask *dataTask = [defaultSession dataTaskWithRequest:headRequest
        completionHandler:^(NSData *data, NSURLResponse *response, NSError *error)
    {
        if (!error && response)
        {
            block([(NSHTTPURLResponse *)response statusCode] == 200);
        }
    }];
    [dataTask resume];
}

- (void)yourMethod
{
    [self checkInternet:^(BOOL internet)
    {
         if (internet)
         {
             // "Internet" aka Google URL reachable
         }
         else
         {
             // No "Internet" aka Google URL un-reachable
         }
    }];
}

@Pavel 2013-03-21 08:28:17

Seems like this is the fastest way

@Mustafa 2013-05-09 07:54:34

Caution: In my experience, this solution doesn't work all the time. In many cases the response returned is 403, after taking its sweet time. This solution seemed perfect, but doesn't guarantee 100% results.

@klcjr89 2013-05-10 01:06:45

Let's figure out a way to improve on the code and make it more perfect.

@Kiran Ruth R 2013-10-08 05:29:15

"No google , no internet" ??

@klcjr89 2013-10-15 15:51:08

@KiranRuthR exactly! :)

@klcjr89 2014-02-07 02:57:45

Updated 2/6/14 with better implementation

@prewett 2014-07-28 05:28:57

As of June 2014, this will fail in mainland China, owing to the Chinese government now completely blocking google.com. (google.cn works, though, but in mainland China, no baidu.com, no internet) Probably better to ping whatever server you need to be communicating with.

@Smikey 2015-07-25 13:53:06

Use www.appleiphonecell.com instead - apple created this url for precisely this reason.

@klcjr89 2015-07-25 14:26:50

@Smikey Google's url is more reliable than Apple's

@Smikey 2015-07-25 14:28:39

But it doesn't work in China - this may be an issue for some people. And Apple created it precisely for testing network reachability on iPhone, so it is reliable.

@Septronic 2015-11-09 14:18:08

I used appleiphonecell as it is Apple's own, can be used in China as well, and it's a very fast website. This, in conjunction with your answer provided me with the nearest and fastest solution. Thank you

@eric 2017-02-23 21:20:52

May I suggest an update to your solution, as if there is an error or your block will never be called. (Also, I always check the block for nil, a it will crash if it is) -> BOOL isConnected = NO; if (!error && response) { isConnected = ([(NSHTTPURLResponse *)response statusCode] == 200); } if ( block ) { block(isConnected); }

@eric 2017-02-23 21:26:29

my previous comment was referring to the ObjectiveC solution

@Ammar Mujeeb 2018-12-31 11:36:34

"appleiphonecell.com" is returning 301(moved permenantly) originally and being redirected to apple.com thats why we get 200. But the response is slower than google.com

@klcjr89 2019-01-07 16:10:47

@AmmarMujeeb updated answer to revert back to using google.

@Zsolt 2018-12-13 06:06:53

see Introducing Network.framework: A modern alternative to Sockets https://developer.apple.com/videos/play/wwdc2018/715/ we should get rid of Reachability at some point.

@Shruti Thombre 2018-10-10 05:46:14

Pod `Alamofire` has `NetworkReachabilityManager`, you just have to create one function 

func isConnectedToInternet() ->Bool {
        return NetworkReachabilityManager()!.isReachable
}

@praful argiddi 2018-09-14 07:29:11

Check internet connection availability in (iOS) using Xcode 9 & Swift 4.0

Follow Below steps

Step 1: Create an extension file and give it the name: ReachabilityManager.swift then add the lines of code below.

import Foundation
import SystemConfiguration
public class ConnectionCheck 
{    
   class func isConnectedToNetwork() -> Bool 
   {
    var zeroAddress = sockaddr_in()
    zeroAddress.sin_len = UInt8(MemoryLayout<sockaddr_in>.size)
    zeroAddress.sin_family = sa_family_t(AF_INET)

    guard let defaultRouteReachability = withUnsafePointer(to: &zeroAddress,         
    {
        $0.withMemoryRebound(to: sockaddr.self, capacity: 1) {
            SCNetworkReachabilityCreateWithAddress(nil, $0)
        }
    }) else {
        return false
    }

    var flags: SCNetworkReachabilityFlags = []
    if !SCNetworkReachabilityGetFlags(defaultRouteReachability, &flags) {
        return false
    }

    let isReachable = flags.contains(.reachable)
    let needsConnection = flags.contains(.connectionRequired)

    return (isReachable && !needsConnection)
   }
  }

Step 2: Call the extension above using the code below.

if ConnectionCheck.isConnectedToNetwork()
{
     print("Connected")
     //Online related Business logic
}
else{
     print("disConnected")
     // offline related business logic
}

@iwasrobbed 2010-08-29 23:58:19

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.

@iwasrobbed 2010-10-19 15:21:38

When they talk about the host being reachable, they are actually talking about whether or not a gateway to the host is reachable or not. They don't mean to say that "google.com" or "apple.com" is available, but moreso that a means of getting there is available.

@quantumpotato 2010-12-21 16:46:08

My checkNetworkStatus method is not getting called.. I'm retaining in the init method. Anyone else have this trouble?

@quantumpotato 2010-12-21 17:07:21

Ah - have to call it manually, since the internet connection isn't "Changed" right when you start. In my ConnectionService init: _internetReachable = [[Reachability reachabilityForInternetConnection] retain]; [self checkNetworkStatus]; works. Thanks! +1

@iwasrobbed 2011-06-14 21:33:09

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

@Tudor 2011-06-24 09:17:33

This example is using internetReachable, hostReachable as class members, which, for me, raises memory errors. I solved it by following Apple's example and accessing the object returned with the notification in the observer method.

@tacos_tacos_tacos 2011-08-10 03:29:47

This is great - way better than what I was doing, which was using a built in WS ping method

@SeungUn Ham 2011-08-26 08:15:49

So many Apple Mach-O Linker Error, can anyone make a simple project using this and post it up please? thanks

@Daniel Bowden 2012-01-17 12:43:25

Tip: Make sure no other libraries you have added already contain Reachability. I had linker errors only to realise Sharekit already had Reachability .h & .m included so I had them in the project twice.

@Coyote 2012-03-08 11:35:10

@gonzobrains There are places where google is not reachable for multiple reasons.

@Guy Daher 2012-03-09 12:39:37

Does WWAN include checking 3G connections?

@Snowcrash 2012-04-26 17:53:07

I already have existing Reachability files which are used by ShareKit. If I overwrite those files with the tonymillion version is my app going to break horribly?

@lagos 2012-07-16 13:06:21

You using a BOOL, but if I copy your solution, the BOOL will always be false untill if I initialize it as True. Even when the BOOL is initialize before the notification come.

@beryllium 2012-07-30 07:37:58

and don't forget to release internetReachable and hostReachable in your dealloc or viewWillDisappear or similar method

@Krishnan 2012-09-28 06:47:17

I think this does not work correctly when phone is in airplane mode. Have any of you checked it?

@Hashmat Khalil 2013-02-21 10:21:40

how can one detect network changes if the app is in the background?

@Kaan Dedeoglu 2013-05-06 15:32:11

AFAIK, google.com is blocked in china - what happens to a user running this code in china?

@iwasrobbed 2013-05-06 16:04:47

@KaanDedeoglu It's just an example, use whatever domain you want. It simply checks for a gateway to the internet, not that the domain is actually available.

@Kaan Dedeoglu 2013-05-06 17:33:15

@iWasRobbed thank you for the clarification :)

@Brad Parks 2013-07-30 17:34:20

Note... For approach 1, you'll need to add the "SystemConfiguration framework to the project", or you'll get errors like "_SCError, referenced from":", as detailed here: stackoverflow.com/a/11014062/26510

@Nikolay Dyankov 2013-07-31 14:53:10

Not very reliable. What if google.com is down? </joke>

@wiseindy 2013-08-16 18:55:52

Oh, btw you need to add SystemConfiguration.framework to the project as well (for method 1).

@Bogdan Alexandru 2013-08-29 13:31:11

I'm an Android programmer learning iOS and I'm simply amazed that iOS doesn't have a simple built-in way of checking the internet connection! In Android SDK it's a one-liner.

@iwasrobbed 2013-08-29 23:38:23

@BogdanAlexandru <insert comment here about how Android doesn't have simple built-in api either>

@Bogdan Alexandru 2013-08-30 07:13:24

@iWasRobbed boolean is_internet_connection = (((ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE)).getActiveNet‌​workInfo() != null);

@iwasrobbed 2013-08-30 16:33:06

@BogdanAlexandru I was speaking more broadly, like in-app purchases for example :) Or expansion files... Just have to be happy with what we have.

@Jacky 2014-07-15 02:20:07

however, no method can detect those case that need to log in.

@iwasrobbed 2014-07-15 18:12:39

@Jacky Huh? Detecting internet connection has nothing to do with storing user sessions for log in.

@Smikey 2015-07-25 13:55:32

Use www.appleiphonecell.com instead of google.com - this url was created by apple for precisely this reason.

@kraftydevil 2015-08-21 06:17:34

What types of things are you all using to "Update the UI on the main thread" asynchronously in Method 1#4? NSNotificationCenter?

@kraftydevil 2015-08-21 07:00:32

Where to call testInternetConnection: or how many times to call it. I'm assuming only once?

@kraftydevil 2015-08-25 10:08:21

@iWasRobbed - ty. I found a blog post that spells out exactly what you're talking about: code.tutsplus.com/tutorials/…

@Vicky Dhas 2016-12-27 04:12:06

I used the Method 1 and trying to switch the Wifi on mac to check the status, strange is when wife disconnected unreachability block is called however' when Wifi made ON' the reachable block gets called , immediately the unreachable block calls as well. Why this error.

@ΩlostA 2018-01-19 11:48:58

It doesn't work if I am logged on an antenna wi-fi with no internet connection on it...

@BlueskyMed 2018-12-09 17:31:21

Use of www.appleiphonecell.com is now (2018) a bad choice. It now redirects to Apple.com which is a > 40kB html file. Back to google.com - it is only 11kB. BTW google.com/m is same size but is reported to be slower by 120 msec.

@Tjalsma 2019-04-12 19:52:21

I must say, any answer that starts with "Install via CocoaPods" is not a really an answer.

@iwasrobbed 2019-04-17 11:00:13

@Tjalsma Guessing you've never worked with Reachability before; you're going to want to use a standard solution and not recreate the wheel

@Neph 2019-05-17 12:40:00

I tested your reachability.whenReachable = { reachability in Swift suggestion but it didn't do anything. Instead I'm now using if reachability.connection != .none(Swift 5, latest version of the file) and it's working well (only tested with emulator and wired internet).

@Dev_Tandel 2017-08-10 14:00:17

Swift 3 / Swift 4

You must first import

import SystemConfiguration

You can check internet connection with the following method

func isConnectedToNetwork() -> Bool {

    var zeroAddress = sockaddr_in()
    zeroAddress.sin_len = UInt8(MemoryLayout.size(ofValue: zeroAddress))
    zeroAddress.sin_family = sa_family_t(AF_INET)

    let defaultRouteReachability = withUnsafePointer(to: &zeroAddress) {
        $0.withMemoryRebound(to: sockaddr.self, capacity: 1) {zeroSockAddress in
            SCNetworkReachabilityCreateWithAddress(nil, zeroSockAddress)
        }
    }

    var flags = SCNetworkReachabilityFlags()
    if !SCNetworkReachabilityGetFlags(defaultRouteReachability!, &flags) {
        return false
    }
    let isReachable = (flags.rawValue & UInt32(kSCNetworkFlagsReachable)) != 0
    let needsConnection = (flags.rawValue & UInt32(kSCNetworkFlagsConnectionRequired)) != 0
    return (isReachable && !needsConnection)

}

@Heitor 2019-06-01 05:18:40

This one works fine in MacOS Swift 5, too!! Tks!

@Aleksander Azizi 2012-04-25 12:20:38

You could use Reachability by  (available here).

#import "Reachability.h"

- (BOOL)networkConnection {
    return [[Reachability reachabilityWithHostName:@"www.google.com"] currentReachabilityStatus];
}

if ([self networkConnection] == NotReachable) { /* No Network */ } else { /* Network */ } //Use ReachableViaWiFi / ReachableViaWWAN to get the type of connection.

@Supertecnoboff 2018-10-03 12:24:49

Does this block the main thread?

@Aleksander Azizi 2018-11-08 19:10:33

@Supertecnoboff No, it's async.

@Andrew Zimmer 2011-10-28 20:37:08

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.

@Valerii Pavlov 2011-12-02 10:52:55

Can u describe this code? How does this check works?

@RocketMan 2012-03-07 03:58:06

Works well on iOS3.0 too, thx

@iwasrobbed 2012-05-03 05:29:58

@JezenThomas This doesn't perform the internet check asynchronously, which is why it is "much slimmer"... You should always be doing this asynchronously by subscribing to notifications so that you don't hang up the app on this process.

@Williew 2012-05-05 02:27:24

Thanks, this work even if you are using wifi adsl and adsl is not connected, is exactly what I need.

@Russell Mull 2012-11-20 08:52:42

This leaks memory - the 'readability' structure (object, thing) needs to be freed with CFRelease().

@i_raqz 2013-09-15 05:23:51

@RussellMull ... any idea how to fix the leak?

@ArtOfWarfare 2014-01-30 05:32:41

Weird that this answer predates mine (on a question marked as a duplicate) by 2 years, is exactly the same as mine, but I never saw it until today.

@Artem Zaytsev 2015-09-10 14:01:20

any ideas how to test connection to concrete IP and Port? Like "127.0.0.1:1535"

@ViJay Avhad 2015-12-17 12:14:31

Checking the Internet connection availability in (iOS) Xcode 8 , Swift 3.0

This is simple method for checking the network availability like our device is connected to any network or not. I have managed to translate it to Swift 3.0 and here the final code. The existing Apple Reachability class and other third party libraries seemed to be too complicated to translate to Swift.

This works for both 3G,4G and WiFi connections.

Don’t forget to add “SystemConfiguration.framework” to your project builder.

//Create new swift class file Reachability in your project.
import SystemConfiguration
public class InternetReachability {

class func isConnectedToNetwork() -> Bool {
   var zeroAddress = sockaddr_in(sin_len: 0, sin_family: 0, sin_port: 0, sin_addr: in_addr(s_addr: 0), sin_zero: (0, 0, 0, 0, 0, 0, 0, 0))
   zeroAddress.sin_len = UInt8(sizeofValue(zeroAddress))
   zeroAddress.sin_family = sa_family_t(AF_INET)
   let defaultRouteReachability = withUnsafePointer(&zeroAddress) {
          SCNetworkReachabilityCreateWithAddress(nil, UnsafePointer($0)).takeRetainedValue()
   }
   var flags: SCNetworkReachabilityFlags = 0
   if SCNetworkReachabilityGetFlags(defaultRouteReachability, &flags) == 0 {
          return false
   }
   let isReachable = (flags & UInt32(kSCNetworkFlagsReachable)) != 0
   let needsConnection = (flags & UInt32(kSCNetworkFlagsConnectionRequired)) != 0

   return isReachable && !needsConnection
  }
}

// Check network connectivity from anywhere in project by using this code.
 if InternetReachability.isConnectedToNetwork() == true {
         print("Internet connection OK")
  } else {
         print("Internet connection FAILED")
  }

@Heitor 2019-06-01 05:11:57

MacOS version? Otherwise main question is NOT answered!

@ViJay Avhad 2019-06-01 06:22:47

Please check main answer heading.

@HariKarthick 2016-11-18 07:51:06

Try this:

- (void) connection:(NSURLConnection *)connection didFailWithError:(NSError *)error


if ([self.delegate respondsToSelector:@selector(getErrorResponse:)]) {
    [self.delegate performSelector:@selector(getErrorResponse:) withObject:@"No Network Connection"];
}

UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:@"BMC" message:@"No Network Connection" delegate:self cancelButtonTitle:nil otherButtonTitles:@"OK",nil];
[alertView show];

}

@Mark Rotteveel 2016-11-19 10:13:27

At minimum add an explanation what this code does and how it solves the problem.

@pierre23 2016-10-17 15:29:23

This is for SWIFT 3.0 and async. Most answers are sync solution which is gonna block your main thread if you have a very slow connection. This solution is better but not perfect because it rely on Google to check the connectivity so feel free to use an other url.

func checkInternetConnection(completionHandler:@escaping (Bool) -> Void)
{
    if let url = URL(string: "http://www.google.com/")
    {
        var request = URLRequest(url: url)
        request.httpMethod = "HEAD"
        request.cachePolicy = .reloadIgnoringLocalAndRemoteCacheData
        request.timeoutInterval = 5

        let tast = URLSession.shared.dataTask(with: request, completionHandler:
        {
            (data, response, error) in

            completionHandler(error == nil)
        })
        tast.resume()
    }
    else
    {
        completionHandler(true)
    }
}

@Anny 2015-08-19 06:37:08

  • Step 1: Add the Reachability class in your Project.
  • Step 2: Import the Reachability class
  • Step 3: Create the below function

    - (BOOL)checkNetConnection {
        self.internetReachability = [Reachability reachabilityForInternetConnection];
        [self.internetReachability startNotifier];
        NetworkStatus netStatus = [self.internetReachability currentReachabilityStatus];
        switch (netStatus) {
            case NotReachable:
            {
                return NO;
            }
    
            case ReachableViaWWAN:
            {
                 return YES;
            }
    
            case ReachableViaWiFi:
            {
                 return YES;
            }
        }
    }
    
  • Step 4: Call the function as below:

    if (![self checkNetConnection]) {
        [GlobalFunctions showAlert:@""
                         message:@"Please connect to the Internet!"
                         canBtntitle:nil
                         otherBtnTitle:@"Ok"];
        return;
    }
    else
    {
        Log.v("internet is connected","ok");
    }
    

@noobsmcgoobs 2016-04-22 19:55:07

Apple's docs state this Note: Reachability cannot tell your application if you can connect to a particular host, only that an interface is available that might allow a connection, and whether that interface is the WWAN.

@Maulik Salvi 2014-11-27 07:29:36

  1. Download the Reachability file, https://gist.github.com/darkseed/1182373

  2. And add CFNetwork.framework and 'SystemConfiguration.framework' in framework

  3. Do #import "Reachability.h"


First: Add CFNetwork.framework in framework

Code: ViewController.m

- (void)viewWillAppear:(BOOL)animated
{
    Reachability *r = [Reachability reachabilityWithHostName:@"www.google.com"];
    NetworkStatus internetStatus = [r currentReachabilityStatus];

    if ((internetStatus != ReachableViaWiFi) && (internetStatus != ReachableViaWWAN))
    {
        /// Create an alert if connection doesn't work
        UIAlertView *myAlert = [[UIAlertView alloc]initWithTitle:@"No Internet Connection"   message:NSLocalizedString(@"InternetMessage", nil)delegate:nil cancelButtonTitle:@"Ok" otherButtonTitles:nil];
        [myAlert show];
        [myAlert release];
    }
    else
    {
         NSLog(@"INTERNET IS CONNECT");
    }
}

@Mina Fawzy 2014-10-01 10:49:02

I think this one is the best answer.

"Yes" means connected. "No" means disconnected.

#import "Reachability.h"

 - (BOOL)canAccessInternet
{
    Reachability *IsReachable = [Reachability reachabilityForInternetConnection];
    NetworkStatus internetStats = [IsReachable currentReachabilityStatus];

    if (internetStats == NotReachable)
    {
        return NO;
    }
    else
    {
        return YES;
    }
}

@Rajesh Loganathan 2014-04-15 12:42:05

Very simple.... Try these steps:

Step 1: Add the SystemConfiguration framework into your project.


Step 2: Import the following code into your header file.

#import <SystemConfiguration/SystemConfiguration.h>

Step 3: Use the following method

  • Type 1:

    - (BOOL) currentNetworkStatus {
        [UIApplication sharedApplication].networkActivityIndicatorVisible = NO;
        BOOL connected;
        BOOL isConnected;
        const char *host = "www.apple.com";
        SCNetworkReachabilityRef reachability = SCNetworkReachabilityCreateWithName(NULL, host);
        SCNetworkReachabilityFlags flags;
        connected = SCNetworkReachabilityGetFlags(reachability, &flags);
        isConnected = NO;
        isConnected = connected && (flags & kSCNetworkFlagsReachable) && !(flags & kSCNetworkFlagsConnectionRequired);
        CFRelease(reachability);
        return isConnected;
    }
    

  • Type 2:

    Import header : #import "Reachability.h"

    - (BOOL)currentNetworkStatus
    {
        Reachability *reachability = [Reachability reachabilityForInternetConnection];
        NetworkStatus networkStatus = [reachability currentReachabilityStatus];
        return networkStatus != NotReachable;
    }
    

Step 4: How to use:

- (void)CheckInternet
{
    BOOL network = [self currentNetworkStatus];
    if (network)
    {
        NSLog(@"Network Available");
    }
    else
    {
        NSLog(@"No Network Available");
    }
}

@Haroldo Gondim 2017-10-08 21:37:59

Type 1 worked for me!

@Supertecnoboff 2018-10-03 17:27:18

Is type 1 asynchronous?

@wesley 2019-01-29 11:54:01

I want the type 2 fixes from your answer. I have added the reachability classes and i tried to check the connection verification by using above your answer. it always comes reachable even if i connect with WiFi but it doesn't have the internet connection. WiFi doesn't mean that it is having internet connection. I wanna verify internet connection even it has WiFi connectivity. Can you please help me out?

@Paresh Hirpara 2014-04-05 11:16:36

First: Add CFNetwork.framework in framework

Code: ViewController.m

#import "Reachability.h"

- (void)viewWillAppear:(BOOL)animated
{
    Reachability *r = [Reachability reachabilityWithHostName:@"www.google.com"];
    NetworkStatus internetStatus = [r currentReachabilityStatus];

    if ((internetStatus != ReachableViaWiFi) && (internetStatus != ReachableViaWWAN))
    {
        /// Create an alert if connection doesn't work
        UIAlertView *myAlert = [[UIAlertView alloc]initWithTitle:@"No Internet Connection"   message:NSLocalizedString(@"InternetMessage", nil)delegate:nil cancelButtonTitle:@"Ok" otherButtonTitles:nil];
        [myAlert show];
        [myAlert release];
    }
    else
    {
         NSLog(@"INTERNET IS CONNECT");
    }
}

@user2538944 2014-02-21 11:44:30

Apart from reachability you may also use the Simple Ping helper library. It works really nice and is simple to integrate.

@Piyush Dubey 2014-01-07 09:04:48

I found it simple and easy to use library SimplePingHelper.

Sample code: chrishulbert/SimplePingHelper (GitHub)

@Tony 2013-12-04 18:17:46

To do this yourself is extremely simple. The following method will work. Just be sure to not allow a hostname protocol such as HTTP, HTTPS, etc. to be passed in with the name.

-(BOOL)hasInternetConnection:(NSString*)urlAddress
{
    SCNetworkReachabilityRef ref = SCNetworkReachabilityCreateWithName(kCFAllocatorDefault, [urlAddress UTF8String]);
    SCNetworkReachabilityFlags flags;
    if (!SCNetworkReachabilityGetFlags(ref, &flags))
    {
        return NO;
    }
    return flags & kSCNetworkReachabilityFlagsReachable;
}

It is quick simple and painless.

@iProgrammer 2013-11-09 09:58:55

There is also another method to check Internet connection using the iPhone SDK.

Try to implement the following code for the network connection.

#import <SystemConfiguration/SystemConfiguration.h>
#include <netdb.h>

/**
     Checking for network availability. It returns
     YES if the network is available.
*/
+ (BOOL) connectedToNetwork
{

    // Create zero addy
    struct sockaddr_in zeroAddress;
    bzero(&zeroAddress, sizeof(zeroAddress));
    zeroAddress.sin_len = sizeof(zeroAddress);
    zeroAddress.sin_family = AF_INET;

    // Recover reachability flags
    SCNetworkReachabilityRef defaultRouteReachability =
        SCNetworkReachabilityCreateWithAddress(NULL, (struct sockaddr *)&zeroAddress);
    SCNetworkReachabilityFlags flags;

    BOOL didRetrieveFlags = SCNetworkReachabilityGetFlags(defaultRouteReachability, &flags);
    CFRelease(defaultRouteReachability);

    if (!didRetrieveFlags)
    {
        printf("Error. Could not recover network reachability flags\n");
        return NO;
    }

    BOOL isReachable = ((flags & kSCNetworkFlagsReachable) != 0);
    BOOL needsConnection = ((flags & kSCNetworkFlagsConnectionRequired) != 0);

    return (isReachable && !needsConnection) ? YES : NO;
}

@Himanshu Mahajan 2013-10-18 06:19:31

Import Reachable.h class in your ViewController, and use the following code to check connectivity:

     #define hasInternetConnection [[Reachability reachabilityForInternetConnection] isReachable]
     if (hasInternetConnection){
           // To-do block
     }

@Nikel Arteta 2015-02-06 10:54:34

Your answer is exactly what I'm searching for. You sir deserves a vote up xD

@K.D 2013-09-17 10:28:45

Get the Reachabilty class from https://github.com/tonymillion/Reachability, add the system configuration framework in your project, do import Reachability.h in your class and implement the custom methods as below:

- (BOOL)isConnectedToInternet
{
    //return NO; // Force for offline testing
    Reachability *hostReach = [Reachability reachabilityForInternetConnection];
    NetworkStatus netStatus = [hostReach currentReachabilityStatus];
    return !(netStatus == NotReachable);
}

@Mark Amery 2013-09-17 11:37:17

-1; adds nothing to this thread that the accepted answer doesn't already cover better, IMO. Also, your entire method body can just be replaced with return [[Reachability reachabilityForInternetConnection] isReachable];

@Huy Tran 2013-08-31 17:13:09

Use http://huytd.github.io/datatify/. It's easier than adding libraries and write code by yourself.

@Durai Amuthan.H 2013-07-10 12:42:53

The Reachability class is OK to find out if the Internet connection is available to a device or not...

But in case of accessing an intranet resource:

Pinging the intranet server with the reachability class always returns true.

So a quick solution in this scenario would be to create a web method called pingme along with other webmethods on the service. The pingme should return something.

So I wrote the following method on common functions

-(BOOL)PingServiceServer
{
    NSURL *url=[NSURL URLWithString:@"http://www.serveraddress/service.asmx/Ping"];

    NSMutableURLRequest *urlReq=[NSMutableURLRequest requestWithURL:url];

    [urlReq setTimeoutInterval:10];

    NSURLResponse *response;

    NSError *error = nil;

    NSData *receivedData = [NSURLConnection sendSynchronousRequest:urlReq
                                                 returningResponse:&response
                                                             error:&error];
    NSLog(@"receivedData:%@",receivedData);

    if (receivedData !=nil)
    {
        return YES;
    }
    else
    {
        NSLog(@"Data is null");
        return NO;
    }
}

The above method was so useful for me, so whenever I try to send some data to the server I always check the reachability of my intranet resource using this low timeout URLRequest.

@Latika Tiwari 2013-06-07 13:53:13

First download the reachability class and put reachability.h and reachabilty.m file in your Xcode.

The best way is to make a common Functions class (NSObject) so that you can use it any class. These are two methods for a network connection reachability check:

+(BOOL) reachabiltyCheck
{
    NSLog(@"reachabiltyCheck");
    BOOL status =YES;
    [[NSNotificationCenter defaultCenter] addObserver:self
                                          selector:@selector(reachabilityChanged:)
                                          name:kReachabilityChangedNotification
                                          object:nil];
    Reachability * reach = [Reachability reachabilityForInternetConnection];
    NSLog(@"status : %d",[reach currentReachabilityStatus]);
    if([reach currentReachabilityStatus]==0)
    {
        status = NO;
        NSLog(@"network not connected");
    }
    reach.reachableBlock = ^(Reachability * reachability)
    {
        dispatch_async(dispatch_get_main_queue(), ^{
        });
    };
    reach.unreachableBlock = ^(Reachability * reachability)
    {
        dispatch_async(dispatch_get_main_queue(), ^{
        });
    };
    [reach startNotifier];
    return status;
}

+(BOOL)reachabilityChanged:(NSNotification*)note
{
    BOOL status =YES;
    NSLog(@"reachabilityChanged");
    Reachability * reach = [note object];
    NetworkStatus netStatus = [reach currentReachabilityStatus];
    switch (netStatus)
    {
        case NotReachable:
            {
                status = NO;
                NSLog(@"Not Reachable");
            }
            break;

        default:
            {
                if (!isSyncingReportPulseFlag)
                {
                    status = YES;
                    isSyncingReportPulseFlag = TRUE;
                    [DatabaseHandler checkForFailedReportStatusAndReSync];
                }
            }
            break;
    }
    return status;
}

+ (BOOL) connectedToNetwork
{
    // Create zero addy
    struct sockaddr_in zeroAddress;
    bzero(&zeroAddress, sizeof(zeroAddress));
    zeroAddress.sin_len = sizeof(zeroAddress);
    zeroAddress.sin_family = AF_INET;

    // Recover reachability flags
    SCNetworkReachabilityRef defaultRouteReachability = SCNetworkReachabilityCreateWithAddress(NULL, (struct sockaddr *)&zeroAddress);
    SCNetworkReachabilityFlags flags;
    BOOL didRetrieveFlags = SCNetworkReachabilityGetFlags(defaultRouteReachability, &flags);
    CFRelease(defaultRouteReachability);
    if (!didRetrieveFlags)
    {
        NSLog(@"Error. Could not recover network reachability flags");
        return NO;
    }
    BOOL isReachable = flags & kSCNetworkFlagsReachable;
    BOOL needsConnection = flags & kSCNetworkFlagsConnectionRequired;
    BOOL nonWiFi = flags & kSCNetworkReachabilityFlagsTransientConnection;
    NSURL *testURL = [NSURL URLWithString:@"http://www.apple.com/"];
    NSURLRequest *testRequest = [NSURLRequest requestWithURL:testURL  cachePolicy:NSURLRequestReloadIgnoringLocalCacheData timeoutInterval:20.0];
    NSURLConnection *testConnection = [[NSURLConnection alloc] initWithRequest:testRequest delegate:self];
    return ((isReachable && !needsConnection) || nonWiFi) ? (testConnection ? YES : NO) : NO;
}

Now you can check network connection in any class by calling this class method.

@IOS Rocks 2012-11-22 11:46:16

- (void)viewWillAppear:(BOOL)animated
{
    NSString *URL = [NSString stringWithContentsOfURL:[NSURL URLWithString:@"http://www.google.com"]];

    return (URL != NULL ) ? YES : NO;
}

Or use the Reachability class.

There are two ways to check Internet availability using the iPhone SDK:

1. Check the Google page is opened or not.

2. Reachability Class

For more information, please refer to Reachability (Apple Developer).

@kleopatra 2012-11-22 11:48:01

please take a bit more care of your formatting ...

@IOS Rocks 2012-11-22 12:04:50

There are two way to check internet availbility in iPhone SDK 1)Check the Google page is opened or not.

@iwasrobbed 2013-03-25 23:05:10

-1 : This is a synchronous method that will block the main thread (the one that the app UI is changed on) while it tries to connect to google.com. If your user is on a very slow data connection, the phone will act like the process is unresponsive.

@Erik 2012-05-14 22:25:53

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).

@rwyland 2012-09-23 05:46:37

I really like this idea, but I would say for the 99.999% reliability while maintaining a small response size, go with www.google.com/m which is the mobile view for google.

@Sebyddd 2014-05-15 13:27:02

Awesome solution @Erik. What i also recommend you is to use www.google.com, instead of www.google.com/m, as rwyland said. It's weird, but from my test the mobile version always takes about 120ms more than the www.google.com

@Brad Thomas 2014-10-07 17:44:18

Apple docs recommend not to do this since it can block the thread on a slow network, can cause app to be terminated in iOS

@Erik 2015-08-08 13:02:33

Thanks for the positive feedback, agree that www.google.com/m is the best solution because of reliability!

@Erik 2015-11-11 14:16:06

Also true that this will block the thread. That's why I'm using an extremely small website. Again, it's simple, not elegant.

@ingconti 2017-08-16 10:25:42

do not use syncronous calls.. as Apple states. (and note that syncronsus call will wrap an asyn call.. :) )

@ingconti 2017-08-24 07:40:47

dont use Async code "masked" as async. Doing do you can end up waiting forever (App stuck) if for example DNS are not set.. call will block indefinitely.

@mxcl 2018-04-03 15:28:03

LOL, I’m sure Google appreciate you suggesting people use them as an Internet check resource.

@Alex 2011-11-07 20:17:53

A version on Reachability for iOS 5 is darkseed/Reachability.h. It's not mine! =)

Related Questions

Sponsored Content

23 Answered Questions

[SOLVED] How can I Remove .DS_Store files from a Git repository?

  • 2008-09-20 09:15:50
  • John Topley
  • 491924 View
  • 1078 Score
  • 23 Answer
  • Tags:   macos git gitignore

24 Answered Questions

[SOLVED] Where is JAVA_HOME on macOS Mojave (10.14) to Lion (10.7)?

  • 2011-07-05 20:19:34
  • Olivier Refalo
  • 447040 View
  • 536 Score
  • 24 Answer
  • Tags:   java macos

14 Answered Questions

[SOLVED] Check for internet connection with Swift

26 Answered Questions

[SOLVED] How do I sort an NSMutableArray with custom objects in it?

91 Answered Questions

22 Answered Questions

[SOLVED] How do I check if a string contains another string in Objective-C?

21 Answered Questions

[SOLVED] How do I install pip on macOS or OS X?

36 Answered Questions

[SOLVED] How can I disable the UITableView selection?

36 Answered Questions

[SOLVED] How to check iOS version?

  • 2010-07-26 23:30:11
  • John
  • 426202 View
  • 816 Score
  • 36 Answer
  • Tags:   ios objective-c

19 Answered Questions

[SOLVED] How do I create delegates in Objective-C?

Sponsored Content