How to check internet connection on iOS device? [duplicate]
Asked Answered
M

10

15

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.

Metallo answered 31/7, 2015 at 9:22 Comment(2)
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 serverMetallo
You can also see here: https://mcmap.net/q/822248/-check-if-iphone-is-connected-to-the-internet-duplicate/33447730#33447730Harmonicon
H
21

Use this code and import Reachability.h file

if ([[Reachability reachabilityForInternetConnection]currentReachabilityStatus]==NotReachable)
    {
         //connection unavailable
    }
    else
    {
         //connection available
    }
Hedve answered 31/7, 2015 at 9:24 Comment(5)
i could not find the Reachability.h file!Metallo
@Metallo Download and put this class in your project. github.com/tonymillion/ReachabilityHedve
@Metallo Try #import "Reachability.h". In my x-code, it doesn't show up in auto-suggestion but the code compilesSilken
in this link get Reachability Class:- github.com/tonymillion/Reachability/blob/master/Reachability.hSoapberry
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?Rossierossing
T
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.

Tempting answered 31/7, 2015 at 10:50 Comment(0)
T
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");
   }

 }
Tedman answered 31/7, 2015 at 9:30 Comment(1)
This solution will not work if the device has been connected to 3G/LTE.Ketcham
H
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);    
}
Hocuspocus answered 31/7, 2015 at 11:15 Comment(1)
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?Rossierossing
A
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];
Auguste answered 7/3, 2017 at 7:33 Comment(0)
L
2

Using Alamofire library:

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

if (isReachable) {
    //Has internet
}else{
    //No internet
}
Latona answered 18/9, 2017 at 17:41 Comment(2)
This also only checks if the device is connected to a network and not if the network is connected to the internet.Grefer
please see my new answerAuthority
F
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.

Frogmouth answered 4/8, 2017 at 10:33 Comment(0)
L
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
}
Latona answered 31/10, 2017 at 22:35 Comment(0)
C
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.

Crudity answered 31/7, 2015 at 9:48 Comment(0)
A
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
}
Alveta answered 26/9, 2016 at 8:59 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.