16

I'm wondering how I can check if the user is connect to internet through WIFI or cellular data 3G or 4G.

Also I don't want to check if a website is reachable or not, the thing that I want to check if there is internet on the device or not. I tried to look over the internet all that I see is that they check if the website is reachable or not using the Rechability class.

I want to check if the user has internet or not when he opens my application.

I'm using Xcode6 with Objective-C.

Eric Aya
  • 68,765
  • 33
  • 165
  • 232
SniperCoder
  • 785
  • 1
  • 10
  • 23
  • my question is not duplicated, this tutorial is checking for google server reachability, however my question is how to check the internet without trying to connect to a website server – SniperCoder Jul 31 '15 at 09:34
  • You can also see here: [http://stackoverflow.com/questions/6129219/check-if-iphone-is-connected-to-the-internet/33447730#33447730](http://stackoverflow.com/questions/6129219/check-if-iphone-is-connected-to-the-internet/33447730#33447730) – Manish Verma Oct 31 '15 at 03:28

10 Answers10

21

Use this code and import Reachability.h file

if ([[Reachability reachabilityForInternetConnection]currentReachabilityStatus]==NotReachable)
    {
         //connection unavailable
    }
    else
    {
         //connection available
    }
Jay Bhalani
  • 4,234
  • 8
  • 33
  • 45
  • i could not find the Reachability.h file! – SniperCoder Jul 31 '15 at 09:46
  • @SniperCoder Download and put this class in your project. https://github.com/tonymillion/Reachability – Jay Bhalani Jul 31 '15 at 09:53
  • @SniperCoder Try #import "Reachability.h". In my x-code, it doesn't show up in auto-suggestion but the code compiles – Astha Gupta Jul 29 '17 at 07:12
  • in this link get Reachability Class:- https://github.com/tonymillion/Reachability/blob/master/Reachability.h – Ramani Hitesh Mar 27 '18 at 13:23
  • I have added the reachability classes and i tried to check the connection verification by using above your answer. it always comes under 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? – wesley Jan 29 '19 at 11:49
6

First Download Reachability classes from this Link:
Rechability from Github

Add Instance of Reachability in AppDelegate.h

@property (nonatomic) Reachability *hostReachability;
@property (nonatomic) Reachability *internetReachability;
@property (nonatomic) Reachability *wifiReachability;

Import Reachability in your AppDelegate and just copy and past this code in your Appdelegate.m

- (id)init
{
    self = [super init];
    if (self != nil)
    {
        //[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(reachabilityChanged:) name:kReachabilityChangedNotification object:nil];
        NSString *remoteHostName = @"www.google.com";
        self.hostReachability = [Reachability reachabilityWithHostName:remoteHostName];
        [self.hostReachability startNotifier];

        self.internetReachability = [Reachability reachabilityForInternetConnection];
        [self.internetReachability startNotifier];

        self.wifiReachability = [Reachability reachabilityForLocalWiFi];
        [self.wifiReachability startNotifier];
    }
    return self;
}  

Add this method in your Common Class.

/*================================================================================================
 Check Internet Rechability
 =================================================================================================*/
+(BOOL)checkIfInternetIsAvailable
{
    BOOL reachable = NO;
    NetworkStatus netStatus = [APP_DELEGATE1.internetReachability currentReachabilityStatus];
    if(netStatus == ReachableViaWWAN || netStatus == ReachableViaWiFi)
    {
        reachable = YES;
    }
    else
    {
        reachable = NO;
    }
    return reachable;
}  

Note that APP_DELEGATE1 Is an instance of AppDelegate

/* AppDelegate object */
#define APP_DELEGATE1 ((AppDelegate*)[[UIApplication sharedApplication] delegate])  

You can check internet connectivity anywhere in app using this method.

Mihir Oza
  • 2,633
  • 3
  • 30
  • 56
3

Hope this helps you to network in Wifi mode only:

Utils.h

 #import <Foundation/Foundation.h>
 @interface Utils : NSObject

 +(BOOL)isNetworkAvailable;

 @end

utils.m

 + (BOOL)isNetworkAvailable
{
      CFNetDiagnosticRef dReference;
      dReference = CFNetDiagnosticCreateWithURL (NULL, (__bridge CFURLRef)[NSURL URLWithString:@"www.apple.com"]);

      CFNetDiagnosticStatus status;
      status = CFNetDiagnosticCopyNetworkStatusPassively (dReference, NULL);

      CFRelease (dReference);

      if ( status == kCFNetDiagnosticConnectionUp )
      {
          NSLog (@"Connection is Available");
          return YES;
      }
      else
      {
          NSLog (@"Connection is down");
          return NO;
      }
    }

//Now use this in required class

- (IBAction)MemberSubmitAction:(id)sender {
   if([Utils isNetworkAvailable] ==YES){

      NSlog(@"Network Connection available");
   }

 }
soumya
  • 3,627
  • 9
  • 33
  • 65
3

it's simple , you can use following method to check internet connection .

-(BOOL)IsConnectionAvailable
{
    Reachability *reachability = [Reachability reachabilityForInternetConnection];

    NetworkStatus networkStatus = [reachability currentReachabilityStatus];

    return !(networkStatus == NotReachable);    
}
Dibin77
  • 138
  • 6
  • I have tried like this. But it always comes as 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? – wesley Jan 29 '19 at 11:57
2

Try This to check internet connected or not

NSURL *url = [NSURL URLWithString:@"http://www.appleiphonecell.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:nil delegateQueue: [NSOperationQueue mainQueue]];

NSURLSessionDataTask *dataTask = [defaultSession dataTaskWithRequest:headRequest
                                                   completionHandler:^(NSData *data, NSURLResponse *response, NSError *error)
                                  {
                                      if (!error && response)
                                      {
                                          block([(NSHTTPURLResponse *)response statusCode] == 200);
                                      }else{
                                          block(FALSE);
                                      }
                                  }];
[dataTask resume];
soumya
  • 3,627
  • 9
  • 33
  • 65
DURGESH
  • 1,585
  • 12
  • 13
1

'Reachability' doesn't work since it won't detect if there is a response from the host or not. It will just check if the client can send out a packet to the host. So even if you are connected to a WiFi network and the WiFi's internet is down or the server is down, you will get a "YES" for reachability.

A better method is to try an HTTP request and verify the response.

Example below:

NSURL *pageToLoadUrl = [[NSURL alloc] initWithString:@"https://www.google.com/"];
NSMutableURLRequest *pageRequest = [NSMutableURLRequest requestWithURL:pageToLoadUrl];
[pageRequest setTimeoutInterval:2.0];
AFHTTPRequestOperation *pageOperation = [[AFHTTPRequestOperation alloc] initWithRequest:pageRequest];
AFRememberingSecurityPolicy *policy = [AFRememberingSecurityPolicy policyWithPinningMode:AFSSLPinningModeNone];
[policy setDelegate:self];
currentPageOperation.securityPolicy = policy;
if (self.ignoreSSLCertificate) {
    NSLog(@"Warning - ignoring invalid certificates");
    currentPageOperation.securityPolicy.allowInvalidCertificates = YES;
}
[pageOperation setCompletionBlockWithSuccess:^(AFHTTPRequestOperation *operation, id responseObject) {
    internetActive = YES;
} failure:^(AFHTTPRequestOperation *operation, NSError *error){
    NSLog(@"Error:------>%@", [error description]);
    internetActive = NO;
}];
[pageOperation start];

Only catch is that the "internetActive" gets updated with a delay upto the timeout mentioned in the above code. You can code inside the callback to act on the status.

Abhijith C R
  • 820
  • 1
  • 8
  • 9
1

Updated answer for Swift 4.0 & AlamoFire:

The answer I posted on Sept 18 is incorrect, it only detects if it is connected to network, not internet. Here is the correct solution using AlamoFire:

1) Create custom Reachability Observer class:

import Alamofire

class ReachabilityObserver {

    fileprivate let reachabilityManager = NetworkReachabilityManager()
    fileprivate var reachabilityStatus: NetworkReachabilityManager.NetworkReachabilityStatus = .unknown

    var isOnline: Bool {
        if (reachabilityStatus == .unknown || reachabilityStatus == .notReachable){
            return false
        }else{
            return true
        }
    }

    static let sharedInstance = ReachabilityObserver()
    fileprivate init () {
        reachabilityManager?.listener = {
            [weak self] status in

            self?.reachabilityStatus = status
            NotificationCenter.default.post(
                name: NSNotification.Name(rawValue: ClickUpConstants.ReachabilityStateChanged),
                object: nil)
        }
        reachabilityManager?.startListening()
    }
}

2) Initialize on app start up

func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
     _ = ReachabilityObserver.sharedInstance
     return true
}

3) Use this anywhere in your app to detect if online, such as in view did load, or when action occurs

if (ReachabilityObserver.sharedInstance.isOnline){
    //User is online
}else{
    //User is not online
}
Josh O'Connor
  • 4,182
  • 6
  • 48
  • 81
0

Try this

check this link for Reachability file

Reachability

import this file in your .m and then write code

//This is to check internet connection

  BOOL hasInternetConnection = [[Reachability reachabilityForInternetConnection] isReachable];
    if (hasInternetConnection) {
               // your code
    }

Hope it helps.

Pradumna Patil
  • 2,062
  • 3
  • 15
  • 42
0
Reachability* reachability = [Reachability reachabilityWithHostName:@"www.google.com"];
NetworkStatus internetStatus = [reachability currentReachabilityStatus];

 if(remoteHostStatus == ReachableViaWWAN || remoteHostStatus == ReachableViaWiFi)

{


     //my web-dependent code
}
else {
    //there-is-no-connection warning
}
Anurag Sharma
  • 2,823
  • 1
  • 21
  • 38
0

Using Alamofire library:

let reachabilityManager = NetworkReachabilityManager()
let isReachable = reachabilityManager.isReachable

if (isReachable) {
    //Has internet
}else{
    //No internet
}
Josh O'Connor
  • 4,182
  • 6
  • 48
  • 81