How can I check whether the app is connected to the internet or not?
currently, I am using this code in my appdelegate.m file
dispatch_queue_t connectivityThread = dispatch_queue_create("com.gm.kart.connectivity", NULL);
dispatch_async(connectivityThread, ^{
while (true){
if([GMMConnectivity hasConnectivity])
NSLog(#"%#", #"connected");
else
NSLog(#"Not connected");
usleep(10000000);
}
});
and when I click my login button I want to do a check whether the internet is connected or not using NSnotificationcenter?
Please help me
After download bellow example.
http://developer.apple.com/iphone/library/samplecode/Reachability/index.html
you can use it in your Project like bellow steps:-
included Apple's Reachability.h & .m from their Reachability example.
add the SystemConfiguration framework.
put bellow method in to your appdelegare.m file:-
- (BOOL) connectedToNetwork{
Reachability* reachability = [Reachability reachabilityWithHostName:#"google.com"];
NetworkStatus remoteHostStatus = [reachability currentReachabilityStatus];
if(remoteHostStatus == NotReachable)
{
isInternet =NO;
}
else if (remoteHostStatus == ReachableViaWWAN)
{
isInternet = TRUE;
}
else if (remoteHostStatus == ReachableViaWiFi)
{ isInternet = TRUE;
}
return isInternet;
}
isInternet is a BOOL declear in to your .h class
as per your code:-
dispatch_queue_t connectivityThread = dispatch_queue_create("com.GMM.assamkart.connectivity", NULL);
dispatch_async(connectivityThread, ^{
while (true){
isInternet =[self connectedToNetwork];
if (isInternet)
{
NSLog(#"connected");
}
else
{
NSLog(#"Not connected");
}
// usleep(10000000);
}
});
-(BOOL) connectedToInternet
{
NSString *URLString = [NSString stringWithContentsOfURL:[NSURL URLWithString:#"http://www.google.com"]];
return ( URLString != NULL ) ? YES : NO;
}
Related
This question already has answers here:
How can I check for an active Internet connection on iOS or macOS?
(46 answers)
Closed 5 years ago.
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.
Use this code and import Reachability.h file
if ([[Reachability reachabilityForInternetConnection]currentReachabilityStatus]==NotReachable)
{
//connection unavailable
}
else
{
//connection available
}
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.
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);
}
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");
}
}
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];
Using Alamofire library:
let reachabilityManager = NetworkReachabilityManager()
let isReachable = reachabilityManager.isReachable
if (isReachable) {
//Has internet
}else{
//No internet
}
'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.
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
}
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.
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
}
We need when wifi connected in iPhone mobile.We need open app-story in browser automatically.i.e We have 4 wifi's Himansu,hits,poll,hotspot.We need When wifi connect Humans after connected it's redirect to below link
https://itunes.apple.com/in/app/facebook/id284882215?mt=8
Please give me any idea.First tell me it's possible or not
Using the code apple provide here
Reachability *reach = [Reachability reachabilityForInternetConnection];
[reach startNotifier];
NetworkStatus status = [reach currentReachabilityStatus];
if(status == NotReachable)
{
//No internet
}
else if (status == ReachableViaWiFi)
{
//WiFi
[[UIApplication sharedApplication] openURL:[NSURL URLWithString:#"https://itunes.apple.com/in/app/facebook/id284882215?mt=8"]];
}
else if (status == ReachableViaWWAN)
{
//3G
[[UIApplication sharedApplication] openURL:[NSURL URLWithString:#"https://itunes.apple.com/in/app/facebook/id284882215?mt=8"]];
}
getting Wifi network Name
Step 1:
import the framework #import <SystemConfiguration/CaptiveNetwork.h>
Step -2
implement the method in
CFArrayRef myArray = CNCopySupportedInterfaces();
CFDictionaryRef myDict = CNCopyCurrentNetworkInfo(CFArrayGetValueAtIndex(myArray, 0));
NSLog(#"Connected at:%#",myDict);
NSDictionary *myDictionary = (__bridge_transfer NSDictionary*)myDict;
NSString * SSID = [myDictionary objectForKey:#"SSID"];
NSLog(#"bssid is %#", SSID);
// your console output is just like
SSID = "Eqra'aOrange";
Step - 3
now you check your condition
if ([SSID isEqualToString:#"Himansu"])
{
// customize your code
}
else
{
// do your stuff
}
In iPhone 5S WiFi detected as 3G and in my iPhone 4 it's normal.
Both in iOS 7.1.
In some devices it happens as well.
WiFi disabled and 3G connected, I double checked to see if internet connection is ok and indeed it's ok in device itself.
Any idea why?
Edit 1:
Code below:
- (void)registerReachabilityNotification
{
[[NSNotificationCenter defaultCenter] addObserver:self
selector:#selector(checkNetworkStatus:)
name:kReachabilityChangedNotification object:nil];
Reachability *reach = [Reachability reachabilityForInternetConnection];
[reach startNotifier];
NSNotification *note = [[NSNotification alloc] initWithName:kReachabilityChangedNotification object:reach userInfo:nil];
[self checkNetworkStatus:note];
}
- (void)checkNetworkStatus:(NSNotification*)notification
{
Reachability *reach = notification.object;
NSParameterAssert([reach isKindOfClass: [Reachability class]]);
NetworkStatus internetStatus = [reach currentReachabilityStatus];
switch (internetStatus)
{
case NotReachable:
{
NSLog(#"No internet connection.");
break;
}
case ReachableViaWiFi:
{
NSLog(#"The internet is working via WIFI.");
break;
}
case ReachableViaWWAN:
{
NSLog(#"The internet is working via WWAN.");
break;
}
}
}
Edit 1:
This code:
NetworkStatus nStats = [[Reachability reachabilityForLocalWiFi] currentReachabilityStatus];
if (nStats != ReachableViaWiFi) {
NSLog(#"nStats != ReachableViaWiFi");
}
if (nStats == ReachableViaWiFi) {
NSLog(#"WIFI");
}
else if (nStats == ReachableViaWWAN) {
NSLog(#"WWAN");
}
else if (nStats == NotReachable) {
NSLog(#"not reachable");
}
else {
NSLog(#"undetermined reachability.");
}
Give me this:
Reachability Flag Status: WR t------ localWiFiStatusForFlags
nStats != ReachableViaWiFi
not reachable
My method was completely wrong, below code for correct way:
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
NSLog(#"CONNECTION: %#", NSStringFromNetworkStatus([MobileControlHandler checkConnection]));
return YES;
}
+ (NetworkStatus)checkConnection
{
NetworkStatus wifiStatus = [[Reachability reachabilityForLocalWiFi] currentReachabilityStatus];
NetworkStatus internetStatus = [[Reachability reachabilityForInternetConnection] currentReachabilityStatus];
if (wifiStatus == ReachableViaWiFi) {
return ReachableViaWiFi;
}
else if (wifiStatus != ReachableViaWiFi && internetStatus == ReachableViaWWAN) {
return ReachableViaWWAN;
}
else {
return NotReachable;
}
}
FOUNDATION_EXPORT NSString *NSStringFromNetworkStatus(NetworkStatus netStatus)
{
if (netStatus == ReachableViaWiFi) {
return #"ReachableViaWiFi";
} else if (netStatus == ReachableViaWWAN) {
return #"ReachableViaWWAN";
} else if (netStatus == NotReachable) {
return #"NotReachable";
} else {
return #"Undetermined reachbility flag";
}
}
Plot:
Reachability Flag Status: WR t------ localWiFiStatusForFlags
Reachability Flag Status: WR t----l- networkStatusForFlags
CONNECTION: ReachableViaWWAN
Just download new Reachability class from Apple
https://developer.apple.com/library/ios/samplecode/Reachability/Introduction/Intro.html
it will work on ios 8 too.
For more interacting things about iOS app development, Checkout
https://appengineer.in/
#import <Reachability.h>
It's a singleton so you can start using it right away.
Ex:
if ([Reachability currentReachabilityStatus] == NotReachable) {
...
}
I start monitoring like this in my AppDelegate:
[[AFNetworkReachabilityManager sharedManager] startMonitoring];
On my root controller I then need to check if reachability is available and I perform this action to decide how to draw my UI:
AFNetworkReachabilityManager *manager = [AFNetworkReachabilityManager sharedManager];
NSLog(#"%s - %#", __FUNCTION__, AFStringFromNetworkReachabilityStatus([manager networkReachabilityStatus]));
switch ([manager networkReachabilityStatus]){
case AFNetworkReachabilityStatusNotReachable:
[self showNetworkUnreachable];
break;
default:
[self hideNetworkUnreachable];
}
My issue is that here status is always unknown even if the device has connection.
Possibly AfNetworking is not the right tool to be used here. Any suggestion?
Not working in my case too. I used that instead:
- (BOOL)isInternetConnectionAvailable
{
Reachability *reachability = [Reachability reachabilityForInternetConnection];
NetworkStatus internetStatus = [reachability currentReachabilityStatus];
if (internetStatus != NotReachable) {
return YES;
}
else
{
NSLog(#"NO INTERNET CONNECTION");
return NO;
}
}
Currently i am using the class by apple reachability.m/.h and it works, except it notifies me for any change, where as i would like to only notify the user if the network is not reachable. Currently if i have a internet connection and then loose the network it tells me. However when you reconnect to the network it also tells me, which i do not want. I want it to only tell me when there is a loss/no network.
I believe it has something to do with the call:
- (void)viewWillAppear:(BOOL)animated
{
// check for internet connection
[[NSNotificationCenter defaultCenter]
addObserver:self
selector:#selector(checkNetworkStatus:)
name:kReachabilityChangedNotification
object:nil];
internetReachable = [[Reachability
reachabilityForInternetConnection] retain];
[internetReachable startNotifier];
// check if a pathway to a random host exists
hostReachable = [[Reachability reachabilityWithHostName:
#"www.google.ca"] retain];
[hostReachable startNotifier];
// now patiently wait for the notification
}
when calling -[NSNotificationCenter addObserver:selector:name:object:], does the name have any other function then being literally a name? this is my first time using NSNotificationCenter so i am not well versed in this matter.
EDIT:
Here is my checkNetworkStatus function: (The problem is i am getting "NotReachable" as the network connection is coming back and NSAlert goes off multiple times)
- (void) checkNetworkStatus:(NSNotification *)notice
{
// called after network status changes
NetworkStatus internetStatus = [internetReachable currentReachabilityStatus];
switch (internetStatus)
{
case NotReachable:
{
UIAlertView * alert = [[UIAlertView alloc] initWithTitle:#"Network Failed" message:#"Please check your connection and try again." delegate:nil cancelButtonTitle:#"OK" otherButtonTitles:nil ];
[alert show];
NSLog(#"The internet is down.");
break;
}
case ReachableViaWiFi:
{
NSLog(#"The internet is working via WIFI.");
break;
}
case ReachableViaWWAN:
{
NSLog(#"The internet is working via WWAN.");
break;
}
}
NetworkStatus hostStatus = [hostReachable currentReachabilityStatus];
switch (hostStatus)
{
case NotReachable:
{
NSLog(#"A gateway to the host server is down.");
break;
}
case ReachableViaWiFi:
{
NSLog(#"A gateway to the host server is working via WIFI.");
break;
}
case ReachableViaWWAN:
{
NSLog(#"A gateway to the host server is working via WWAN.");
break;
}
}
}
Reachability will send a notification when the status has changed, but what you do with that notification is entirely up to you. If you don't want to tell the user that the network is back, you don't have to.
The "name" parameter in the NSNotificationCenter method indicates what notification you are subscribing to. When an object posts a notification, it does so with a particular name.
If you replace the www.hostname.com with just an IP address, it will only alert once instead of multiple times.
I just started playing around with Reachability and hopefully what I discovered is of use to you.
With regards to multiple 'Not Reachable' while reconnecting, could it be linked to this? Here the poster brought up the definition of 'reachable' for a remote host. I'm guessing while reconnecting the package is not able to go through successfully?
Another possibility is in Reachability Readme.txt
IMPORTANT: Reachability must use DNS to resolve the host name before it
can determine the Reachability of that host, and this may take time on
certain network connections. Because of this, the API will return
NotReachable until name resolution has completed. This delay may be
visible in the interface on some networks.
Maybe give it the IP directly and see if it helps?
With Reachability 2.2, you can add
[hostReach connectionRequired];
before
[internetReachable startNotifier];
to solve this problem.
runmad answered this problem here:
https://stackoverflow.com/a/2157858/623260
I would implement the whole Reachability class, tie it into your code as necessary and remove or comment out parts of Reachability. Just remove, one by one, the things you do not want to be notified of. Obviously, you need a good understanding of obj-c, the Reachability class, notifications, etc., but it can be done.
One thing you can do is unsubscribe to the changed notification NSNotificationCenter removeObserver... while you're processing one in the callback. Add back the observer before returning.
We can check rechability using this code
add class Reachability.h
#import <Foundation/Foundation.h>
#import <SystemConfiguration/SystemConfiguration.h>
typedef enum {
NotReachable = 0,
ReachableViaWiFi,
ReachableViaWWAN
} NetworkStatus;
#define kReachabilityChangedNotification #"kNetworkReachabilityChangedNotification"
#interface Reachability: NSObject
{
BOOL localWiFiRef;
SCNetworkReachabilityRef reachabilityRef;
}
//reachabilityWithHostName- Use to check the reachability of a particular host name.
+ (Reachability*) reachabilityWithHostName: (NSString*) hostName;
//reachabilityWithAddress- Use to check the reachability of a particular IP address.
+ (Reachability*) reachabilityWithAddress: (const struct sockaddr_in*) hostAddress;
//reachabilityForInternetConnection- checks whether the default route is available.
// Should be used by applications that do not connect to a particular host
+ (Reachability*) reachabilityForInternetConnection;
//reachabilityForLocalWiFi- checks whether a local wifi connection is available.
+ (Reachability*) reachabilityForLocalWiFi;
//Start listening for reachability notifications on the current run loop
- (BOOL) startNotifier;
- (void) stopNotifier;
- (NetworkStatus) currentReachabilityStatus;
//WWAN may be available, but not active until a connection has been established.
//WiFi may require a connection for VPN on Demand.
- (BOOL) connectionRequired;
#end
Reachability.m
#import <sys/socket.h>
#import <netinet/in.h>
#import <netinet6/in6.h>
#import <arpa/inet.h>
#import <ifaddrs.h>
#import <netdb.h>
#import <CoreFoundation/CoreFoundation.h>
#import "Reachability.h"
#define kShouldPrintReachabilityFlags 1
static void PrintReachabilityFlags(SCNetworkReachabilityFlags flags, const char* comment)
{
#if kShouldPrintReachabilityFlags
NSLog(#"Reachability Flag Status: %c%c %c%c%c%c%c%c%c %s\n",
(flags & kSCNetworkReachabilityFlagsIsWWAN) ? 'W' : '-',
(flags & kSCNetworkReachabilityFlagsReachable) ? 'R' : '-',
(flags & kSCNetworkReachabilityFlagsTransientConnection) ? 't' : '-',
(flags & kSCNetworkReachabilityFlagsConnectionRequired) ? 'c' : '-',
(flags & kSCNetworkReachabilityFlagsConnectionOnTraffic) ? 'C' : '-',
(flags & kSCNetworkReachabilityFlagsInterventionRequired) ? 'i' : '-',
(flags & kSCNetworkReachabilityFlagsConnectionOnDemand) ? 'D' : '-',
(flags & kSCNetworkReachabilityFlagsIsLocalAddress) ? 'l' : '-',
(flags & kSCNetworkReachabilityFlagsIsDirect) ? 'd' : '-',
comment
);
#endif
}
#implementation Reachability
static void ReachabilityCallback(SCNetworkReachabilityRef target, SCNetworkReachabilityFlags flags, void* info)
{
#pragma unused (target, flags)
NSCAssert(info != NULL, #"info was NULL in ReachabilityCallback");
NSCAssert([(NSObject*) info isKindOfClass: [Reachability class]], #"info was wrong class in ReachabilityCallback");
//We're on the main RunLoop, so an NSAutoreleasePool is not necessary, but is added defensively
// in case someon uses the Reachablity object in a different thread.
NSAutoreleasePool* myPool = [[NSAutoreleasePool alloc] init];
Reachability* noteObject = (Reachability*) info;
// Post a notification to notify the client that the network reachability changed.
[[NSNotificationCenter defaultCenter] postNotificationName: kReachabilityChangedNotification object: noteObject];
[myPool release];
}
- (BOOL) startNotifier
{
BOOL retVal = NO;
SCNetworkReachabilityContext context = {0, self, NULL, NULL, NULL};
if(SCNetworkReachabilitySetCallback(reachabilityRef, ReachabilityCallback, &context))
{
if(SCNetworkReachabilityScheduleWithRunLoop(reachabilityRef, CFRunLoopGetCurrent(), kCFRunLoopDefaultMode))
{
retVal = YES;
}
}
return retVal;
}
- (void) stopNotifier
{
if(reachabilityRef!= NULL)
{
SCNetworkReachabilityUnscheduleFromRunLoop(reachabilityRef, CFRunLoopGetCurrent(), kCFRunLoopDefaultMode);
}
}
- (void) dealloc
{
[self stopNotifier];
if(reachabilityRef!= NULL)
{
CFRelease(reachabilityRef);
}
[super dealloc];
}
+ (Reachability*) reachabilityWithHostName: (NSString*) hostName;
{
Reachability* retVal = NULL;
SCNetworkReachabilityRef reachability = SCNetworkReachabilityCreateWithName(NULL, [hostName UTF8String]);
if(reachability!= NULL)
{
retVal= [[[self alloc] init] autorelease];
if(retVal!= NULL)
{
retVal->reachabilityRef = reachability;
retVal->localWiFiRef = NO;
}
}
return retVal;
}
+ (Reachability*) reachabilityWithAddress: (const struct sockaddr_in*) hostAddress;
{
SCNetworkReachabilityRef reachability = SCNetworkReachabilityCreateWithAddress(kCFAllocatorDefault, (const struct sockaddr*)hostAddress);
Reachability* retVal = NULL;
if(reachability!= NULL)
{
retVal= [[[self alloc] init] autorelease];
if(retVal!= NULL)
{
retVal->reachabilityRef = reachability;
retVal->localWiFiRef = NO;
}
}
return retVal;
}
+ (Reachability*) reachabilityForInternetConnection;
{
struct sockaddr_in zeroAddress;
bzero(&zeroAddress, sizeof(zeroAddress));
zeroAddress.sin_len = sizeof(zeroAddress);
zeroAddress.sin_family = AF_INET;
return [self reachabilityWithAddress: &zeroAddress];
}
+ (Reachability*) reachabilityForLocalWiFi;
{
struct sockaddr_in localWifiAddress;
bzero(&localWifiAddress, sizeof(localWifiAddress));
localWifiAddress.sin_len = sizeof(localWifiAddress);
localWifiAddress.sin_family = AF_INET;
// IN_LINKLOCALNETNUM is defined in <netinet/in.h> as 169.254.0.0
localWifiAddress.sin_addr.s_addr = htonl(IN_LINKLOCALNETNUM);
Reachability* retVal = [self reachabilityWithAddress: &localWifiAddress];
if(retVal!= NULL)
{
retVal->localWiFiRef = YES;
}
return retVal;
}
#pragma mark Network Flag Handling
- (NetworkStatus) localWiFiStatusForFlags: (SCNetworkReachabilityFlags) flags
{
PrintReachabilityFlags(flags, "localWiFiStatusForFlags");
BOOL retVal = NotReachable;
if((flags & kSCNetworkReachabilityFlagsReachable) && (flags & kSCNetworkReachabilityFlagsIsDirect))
{
retVal = ReachableViaWiFi;
}
return retVal;
}
- (NetworkStatus) networkStatusForFlags: (SCNetworkReachabilityFlags) flags
{
PrintReachabilityFlags(flags, "networkStatusForFlags");
if ((flags & kSCNetworkReachabilityFlagsReachable) == 0)
{
// if target host is not reachable
return NotReachable;
}
BOOL retVal = NotReachable;
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
retVal = ReachableViaWiFi;
}
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
retVal = ReachableViaWiFi;
}
}
if ((flags & kSCNetworkReachabilityFlagsIsWWAN) == kSCNetworkReachabilityFlagsIsWWAN)
{
// ... but WWAN connections are OK if the calling application
// is using the CFNetwork (CFSocketStream?) APIs.
retVal = ReachableViaWWAN;
}
return retVal;
}
- (BOOL) connectionRequired;
{
NSAssert(reachabilityRef != NULL, #"connectionRequired called with NULL reachabilityRef");
SCNetworkReachabilityFlags flags;
if (SCNetworkReachabilityGetFlags(reachabilityRef, &flags))
{
return (flags & kSCNetworkReachabilityFlagsConnectionRequired);
}
return NO;
}
- (NetworkStatus) currentReachabilityStatus
{
NSAssert(reachabilityRef != NULL, #"currentNetworkStatus called with NULL reachabilityRef");
NetworkStatus retVal = NotReachable;
SCNetworkReachabilityFlags flags;
if (SCNetworkReachabilityGetFlags(reachabilityRef, &flags))
{
if(localWiFiRef)
{
retVal = [self localWiFiStatusForFlags: flags];
}
else
{
retVal = [self networkStatusForFlags: flags];
}
}
return retVal;
}
#end
and use via direct calling method in appdel class using
[[NSNotificationCenter defaultCenter] addObserver:self selector:#selector(checkNetworkStatus:) name:kReachabilityChangedNotification object:nil];
-(void) checkNetworkStatus:(NSNotification *)notice
{
Reachability* internetReachable;
BOOL isInternetActive;
// called after network status changes
NetworkStatus internetStatus = [internetReachable currentReachabilityStatus];
switch (internetStatus)
{
case NotReachable:
{
NSLog(#"The internet is down.");
isInternetActive = NO;
break;
}
case ReachableViaWiFi:
{
NSLog(#"The internet is working via WIFI.");
isInternetActive = YES;
break;
}
case ReachableViaWWAN:
{
NSLog(#"The internet is working via WWAN.");
isInternetActive = YES;
break;
}
}
NetworkStatus hostStatus = [hostReachable currentReachabilityStatus];
switch (hostStatus)
{
case NotReachable:
{
NSLog(#"A gateway to the host server is down.");
// self.hostActive = NO;
break;
}
case ReachableViaWiFi:
{
NSLog(#"A gateway to the host server is working via WIFI.");
// self.hostActive = YES;
break;
}
case ReachableViaWWAN:
{
NSLog(#"A gateway to the host server is working via WWAN.");
// self.hostActive = YES;
break;
}
}
}