Created
May 25, 2011 00:44
-
-
Save eiffelqiu/990085 to your computer and use it in GitHub Desktop.
Checking network availability on iOS
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include <netinet/in.h> | |
#import <SystemConfiguration/SCNetworkReachability.h> | |
- (BOOL)connectedToNetwork { | |
// Create zero addy | |
struct sockaddr_in zeroAddress; | |
bzero(&zeroAddress, sizeof(zeroAddress)); | |
zeroAddress.sin_len = sizeof(zeroAddress); | |
zeroAddress.sin_family = AF_INET; | |
// Recover reachability flags | |
SCNetworkReachabilityRef defaultRouteReachability = SCNetworkReachabilityCreateWithAddress(NULL, (struct sockaddr*)&zeroAddress); | |
SCNetworkReachabilityFlags flags; | |
BOOL didRetrieveFlags = SCNetworkReachabilityGetFlags(defaultRouteReachability, &flags); | |
CFRelease(defaultRouteReachability); | |
if (!didRetrieveFlags) | |
{ | |
NSLog(@"Error. Could not recover network reachability flags"); | |
return 0; | |
} | |
BOOL isReachable = flags & kSCNetworkFlagsReachable; | |
BOOL needsConnection = flags & kSCNetworkFlagsConnectionRequired; | |
return (isReachable && !needsConnection) ? YES : NO; | |
} | |
// How to use | |
if ([self connectedToNetwork]) { | |
//yes we're connected | |
} | |
else { | |
//no we're not connected | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment