Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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.

like image 781
SniperCoder Avatar asked Jul 31 '15 09:07

SniperCoder


2 Answers

Use this code and import Reachability.h file

if ([[Reachability reachabilityForInternetConnection]currentReachabilityStatus]==NotReachable)
    {
         //connection unavailable
    }
    else
    {
         //connection available
    }
like image 144
Jay Bhalani Avatar answered Oct 06 '22 23:10

Jay Bhalani


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.

like image 38
Mihir Oza Avatar answered Oct 06 '22 22:10

Mihir Oza