0

How to check Internet connectivity is available

I am using apple Reachability class to check the network status by using the below code

-(BOOL)isInternetConnectionAvailable{

    return ([[Reachability reachabilityForInternetConnection]currentReachabilityStatus] == NotReachable)?NO:YES;
}

I am I have hotspot a Mobile then connected that wifi with my iPhone. Then Mobile data is off and hot spot is ON. But the rechability class is returning ReachableViaWiFi How can I check the network have internet.

Vineesh TP
  • 7,025
  • 9
  • 54
  • 102
  • Find your answer: http://stackoverflow.com/questions/1083701/how-to-check-for-an-active-internet-connection-on-ios-or-osx?page=1&tab=oldest#tab-top] – Sumeet Mourya Mar 13 '17 at 13:48

1 Answers1

0

For this you have check internet, for this make a internet validation class and then call that class every place where you are using internet.

In your .h file make a static method, like given below.

#import <Foundation/Foundation.h>

@interface InternetValidation : NSObject {

}

+ (BOOL) connectedToNetwork;

@end

Then, in your .m file

#import "InternetValidation.h"
#import <SystemConfiguration/SCNetworkReachability.h>
#include <netinet/in.h>

@implementation InternetValidation

+ (BOOL) connectedToNetwork
{


    BOOL success = NO;
    const char *host_name = [@"google.com"
                             cStringUsingEncoding:NSASCIIStringEncoding];

    SCNetworkReachabilityRef reachability = SCNetworkReachabilityCreateWithName(NULL,
                                                                                host_name);
    SCNetworkReachabilityFlags flags;
    success = SCNetworkReachabilityGetFlags(reachability, &flags);
    BOOL isAvailable = success && (flags & kSCNetworkFlagsReachable) && !(flags & kSCNetworkFlagsConnectionRequired);
    if (isAvailable) {
        success = YES;
    }else{
        success = NO;
    }
    //NSLog(@"%d",success);
    return success;

}


@end

Now, Import this class where you want to check internet.

Then Call that internet Class Method like this way.

if ([InternetValidation connectedToNetwork]){
    //Do your code here.
}
else{
    // No Internet;
}
Abhishek Mitra
  • 2,970
  • 3
  • 21
  • 38