如何检查iOS或OSX上的活动Internet连接?
我想检查一下,如果我在iOS上使用Cocoa Touch库或使用Cocoa库的OSX上有Internet连接。
我想出了一个使用NSURL
。 我这样做的方式似乎有点不可靠(因为即使Google有一天可能会倒闭,依靠第三方似乎不好),而我可以检查一下其他网站的反应,如果谷歌没有回应,看起来很浪费,对我的应用程序来说是不必要的开销。
- (BOOL) connectedToInternet { NSString *URLString = [NSString stringWithContentsOfURL:[NSURL URLWithString:@"http://www.google.com"]]; return ( URLString != NULL ) ? YES : NO; }
我做得不好吗? (更不用说stringWithContentsOfURL
在iOS 3.0和OSX 10.4中被弃用),如果是这样,有什么更好的方法来完成这一点?
方法1:使用一个简单的(ARC和GCD兼容)类来完成它
1)将SystemConfiguration
框架添加到项目中,但不要担心将其包含在任何地方
2)将Tony Million的版本Reachability.h
和Reachability.m
到项目中(在这里find: https : //github.com/tonymillion/Reachability )
3)更新界面部分
#import "Reachability.h" // Add this to the interface in the .m file of your view controller @interface MyViewController () { Reachability *internetReachableFoo; } @end
4)然后在您可以调用的视图控制器的.m文件中实现此方法
// Checks if we have an internet connection or not - (void)testInternetConnection { internetReachableFoo = [Reachability reachabilityWithHostname:@"www.google.com"]; // Internet is reachable internetReachableFoo.reachableBlock = ^(Reachability*reach) { // Update the UI on the main thread dispatch_async(dispatch_get_main_queue(), ^{ NSLog(@"Yayyy, we have the interwebs!"); }); }; // Internet is not reachable internetReachableFoo.unreachableBlock = ^(Reachability*reach) { // Update the UI on the main thread dispatch_async(dispatch_get_main_queue(), ^{ NSLog(@"Someone broke the internet :("); }); }; [internetReachableFoo startNotifier]; }
方法2:使用苹果过时的可达性类自己做旧的方法
1)将SystemConfiguration
框架添加到项目中,但不要担心将其包含在任何地方
2)将Apple的版本Reachability.h
和Reachability.m
到项目中( 您可以在这里获得 )
3)添加@class Reachability;
到你正在执行代码的.h文件
4)创build几个实例来检查.h文件的interface
部分:
Reachability* internetReachable; Reachability* hostReachable;
5)在networking状态更新时在.h中添加一个方法:
-(void) checkNetworkStatus:(NSNotification *)notice;
6)将#import "Reachability.h"
添加到您正在执行检查的.m文件中
7)在你正在执行检查的.m文件中,你可以把它放在第一个被称为( init
或viewWillAppear
或viewDidLoad
等)的方法中:
-(void) viewWillAppear:(BOOL)animated { // check for internet connection [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(checkNetworkStatus:) name:kReachabilityChangedNotification object:nil]; internetReachable = [Reachability reachabilityForInternetConnection]; [internetReachable startNotifier]; // check if a pathway to a random host exists hostReachable = [Reachability reachabilityWithHostName:@"www.apple.com"]; [hostReachable startNotifier]; // now patiently wait for the notification }
8)设置通知发送时的方法,并设置任何检查或调用您可能已经设置的任何方法(在我的情况下,我只是设置一个BOOL)
-(void) checkNetworkStatus:(NSNotification *)notice { // called after network status changes NetworkStatus internetStatus = [internetReachable currentReachabilityStatus]; switch (internetStatus) { case NotReachable: { NSLog(@"The internet is down."); self.internetActive = NO; break; } case ReachableViaWiFi: { NSLog(@"The internet is working via WIFI."); self.internetActive = YES; break; } case ReachableViaWWAN: { NSLog(@"The internet is working via WWAN."); self.internetActive = 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; } } }
9)在你的dealloc
或viewWillDisappear
或类似的方法,作为观察者删除自己
-(void) viewWillDisappear:(BOOL)animated { [[NSNotificationCenter defaultCenter] removeObserver:self]; }
注意:可能有一个使用viewWillDisappear
的实例,在这个实例中,你会收到一个内存警告,观察者永远不会注册,所以你也应该考虑到这一点。
注意:您使用的域名无关紧要。 它只是testing任何域的网关。
重要提示: Reachability
类是项目中最常用的类之一,所以您可能会遇到与其他项目(如ShareKit)的命名冲突。 如果发生这种情况,您必须将其中一个Reachability.h
和Reachability.m
文件重命名为其他内容才能解决问题。
我喜欢保持简单。 我这样做的方式是:
//Class.h #import "Reachability.h" #import <SystemConfiguration/SystemConfiguration.h> - (BOOL)connected; //Class.m - (BOOL)connected { Reachability *reachability = [Reachability reachabilityForInternetConnection]; NetworkStatus networkStatus = [reachability currentReachabilityStatus]; return networkStatus != NotReachable; }
然后,每当我想查看是否有连接时,我都会使用它:
if (![self connected]) { // Not connected } else { // Connected. Do some Internet stuff }
此方法不会等待更改的networking状态才能完成任务。 它只是testing你的要求时的状态。
使用苹果的Reachability代码,我创build了一个函数,可以正确检查这个,而不必包含任何类。
将SystemConfiguration.framework包含在您的项目中。
进行一些import:
#import <sys/socket.h> #import <netinet/in.h> #import <SystemConfiguration/SystemConfiguration.h>
现在只需调用这个函数:
/* Connectivity testing code pulled from Apple's Reachability Example: https://developer.apple.com/library/content/samplecode/Reachability */ +(BOOL)hasConnectivity { struct sockaddr_in zeroAddress; bzero(&zeroAddress, sizeof(zeroAddress)); zeroAddress.sin_len = sizeof(zeroAddress); zeroAddress.sin_family = AF_INET; SCNetworkReachabilityRef reachability = SCNetworkReachabilityCreateWithAddress(kCFAllocatorDefault, (const struct sockaddr*)&zeroAddress); if (reachability != NULL) { //NetworkStatus retVal = NotReachable; SCNetworkReachabilityFlags flags; if (SCNetworkReachabilityGetFlags(reachability, &flags)) { if ((flags & kSCNetworkReachabilityFlagsReachable) == 0) { // If target host is not reachable return NO; } 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 return YES; } 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 return YES; } } if ((flags & kSCNetworkReachabilityFlagsIsWWAN) == kSCNetworkReachabilityFlagsIsWWAN) { // ... but WWAN connections are OK if the calling application // is using the CFNetwork (CFSocketStream?) APIs. return YES; } } } return NO; }
它的iOS 5为您testing。
这曾经是正确的答案,但是现在已经过时了,因为您应该订阅可达性通知。 该方法同步检查:
您可以使用Apple的Reachability类。 它也将允许您检查是否启用Wi-Fi:
Reachability* reachability = [Reachability sharedReachability]; [reachability setHostName:@"www.example.com"]; // Set your host name here NetworkStatus remoteHostStatus = [reachability remoteHostStatus]; if (remoteHostStatus == NotReachable) { } else if (remoteHostStatus == ReachableViaWiFiNetwork) { } else if (remoteHostStatus == ReachableViaCarrierDataNetwork) { }
Reachability类不附带SDK,而是这个Apple示例应用程序的一部分。 只需下载它,并将Reachability.h / m复制到您的项目。 另外,您还必须将SystemConfiguration框架添加到您的项目中。
这是一个非常简单的答案:
NSURL *scriptUrl = [NSURL URLWithString:@"http://www.google.com/m"]; NSData *data = [NSData dataWithContentsOfURL:scriptUrl]; if (data) NSLog(@"Device is connected to the Internet"); else NSLog(@"Device is not connected to the Internet");
该url应指向一个非常小的网站。 我在这里使用Google的移动网站,但是如果我有一个可靠的Web服务器,我会上传一个只有一个字符的小文件,以获得最大的速度。
如果检查设备是否连接到互联网是你想做的一切,我肯定会推荐使用这个简单的解决scheme。 如果你需要知道用户如何连接,使用可达性是可行的。
小心:这会在加载网站时暂时阻止您的线程。 在我的情况下,这不是一个问题,但你应该考虑这一点(信贷布拉德指出这一点)。
下面是我在应用程序中的做法:虽然200状态响应代码不能保证任何内容,但对我来说足够稳定。 这不需要像这里发布的NSData答案一样多的加载,因为我只是检查HEAD响应。
SWIFT代码
func checkInternet(flag:Bool, completionHandler:(internet:Bool) -> Void) { UIApplication.sharedApplication().networkActivityIndicatorVisible = true let url = NSURL(string: "http://www.appleiphonecell.com/") let request = NSMutableURLRequest(URL: url!) request.HTTPMethod = "HEAD" request.cachePolicy = NSURLRequestCachePolicy.ReloadIgnoringLocalAndRemoteCacheData request.timeoutInterval = 10.0 NSURLConnection.sendAsynchronousRequest(request, queue:NSOperationQueue.mainQueue(), completionHandler: {(response: NSURLResponse!, data: NSData!, error: NSError!) -> Void in UIApplication.sharedApplication().networkActivityIndicatorVisible = false let rsp = response as! NSHTTPURLResponse? completionHandler(internet:rsp?.statusCode == 200) }) } func yourMethod() { self.checkInternet(false, completionHandler: {(internet:Bool) -> Void in if (internet) { // "Internet" aka Apple's region universal URL reachable } else { // No "Internet" aka Apple's region universal URL un-reachable } }) }
Objective-C代码
typedef void(^connection)(BOOL); - (void)checkInternet:(connection)block { 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:self delegateQueue: [NSOperationQueue mainQueue]]; NSURLSessionDataTask *dataTask = [defaultSession dataTaskWithRequest:headRequest completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) { if (!error && response) { block([(NSHTTPURLResponse *)response statusCode] == 200); } }]; [dataTask resume]; } - (void)yourMethod { [self checkInternet:^(BOOL internet) { if (internet) { // "Internet" aka Apple's region universal URL reachable } else { // No "Internet" aka Apple's region universal URL un-reachable } }]; }
Apple提供示例代码来检查不同types的networking可用性。 或者在iPhone开发者食谱中有一个例子 。
注意:请参阅@ KHG对此答案的评论,关于使用苹果的可达性代码。
您可以使用Re( 可在此处 )使用Reachability
。
#import "Reachability.h" - (BOOL)networkConnection { return [[Reachability reachabilityWithHostName:@"www.google.com"] currentReachabilityStatus]; } if ([self networkConnection] == NotReachable) { /* No Network */ } else { /* Network */ } //Use ReachableViaWiFi / ReachableViaWWAN to get the type of connection.
苹果提供了一个示例应用程序,它完全是这样的
可达性
只有Reachability类已更新。 你现在可以使用:
Reachability* reachability = [Reachability reachabilityWithHostName:@"www.apple.com"]; NetworkStatus remoteHostStatus = [reachability currentReachabilityStatus]; if (remoteHostStatus == NotReachable) { NSLog(@"not reachable");} else if (remoteHostStatus == ReachableViaWWAN) { NSLog(@"reachable via wwan");} else if (remoteHostStatus == ReachableViaWiFi) { NSLog(@"reachable via wifi");}
iOS 5的可达性版本是darkseed / Reachability.h 。 不是我的! =)
这里有一个漂亮的ARC和GCD使用现代化的可达性:
可达性
如果您正在使用AFNetworking
,则可以使用自己的实现来实现互联网可达性状态。
使用AFNetworking
的最好方法是AFHTTPClient
类,并使用这个类来完成你的networking连接。
使用这种方法的优点之一是,当可达性状态改变时,您可以使用blocks
来设置所需的行为。 假设我已经创build了一个AFHTTPClient
的单AFHTTPClient
类(如AFNetworking文档中的“子类注释” 所述 ),我可以这样做:
BKHTTPClient *httpClient = [BKHTTPClient sharedClient]; [httpClient setReachabilityStatusChangeBlock:^(AFNetworkReachabilityStatus status) { if (status == AFNetworkReachabilityStatusNotReachable) { // Not reachable } else { // Reachable } }];
您还可以使用AFNetworkReachabilityStatusReachableViaWWAN
和AFNetworkReachabilityStatusReachableViaWiFi
枚举( 此处更多 )专门检查Wi-Fi或WLAN连接。
我在这个讨论中使用了代码,它似乎工作正常(阅读整个线程!)。
我还没有对每种可能的连接进行详尽的testing(如ad-hoc Wi-Fi)。
很简单….试试这些步骤:
第1步:将SystemConfiguration
框架添加到您的项目中。
第2步:将以下代码导入到您的header
文件中。
#import <SystemConfiguration/SystemConfiguration.h>
第3步:使用以下方法
-
types1:
- (BOOL) currentNetworkStatus { [UIApplication sharedApplication].networkActivityIndicatorVisible = NO; BOOL connected; BOOL isConnected; const char *host = "www.apple.com"; SCNetworkReachabilityRef reachability = SCNetworkReachabilityCreateWithName(NULL, host); SCNetworkReachabilityFlags flags; connected = SCNetworkReachabilityGetFlags(reachability, &flags); isConnected = NO; isConnected = connected && (flags & kSCNetworkFlagsReachable) && !(flags & kSCNetworkFlagsConnectionRequired); CFRelease(reachability); return isConnected; }
-
types2:
导入标题 :
#import "Reachability.h"
- (BOOL)currentNetworkStatus { Reachability *reachability = [Reachability reachabilityForInternetConnection]; NetworkStatus networkStatus = [reachability currentReachabilityStatus]; return networkStatus != NotReachable; }
第四步:如何使用:
- (void)CheckInternet { BOOL network = [self currentNetworkStatus]; if (network) { NSLog(@"Network Available"); } else { NSLog(@"No Network Available"); } }
-(void)newtworkType { NSArray *subviews = [[[[UIApplication sharedApplication] valueForKey:@"statusBar"] valueForKey:@"foregroundView"]subviews]; NSNumber *dataNetworkItemView = nil; for (id subview in subviews) { if([subview isKindOfClass:[NSClassFromString(@"UIStatusBarDataNetworkItemView") class]]) { dataNetworkItemView = subview; break; } } switch ([[dataNetworkItemView valueForKey:@"dataNetworkType"]integerValue]) { case 0: NSLog(@"No wifi or cellular"); break; case 1: NSLog(@"2G"); break; case 2: NSLog(@"3G"); break; case 3: NSLog(@"4G"); break; case 4: NSLog(@"LTE"); break; case 5: NSLog(@"Wifi"); break; default: break; } }
- (void)viewWillAppear:(BOOL)animated { NSString *URL = [NSString stringWithContentsOfURL:[NSURL URLWithString:@"http://www.google.com"]]; return (URL != NULL ) ? YES : NO; }
或者使用Reachability类 。
有两种方法可以使用iPhone SDK检查Internet可用性:
1.检查Google页面是否被打开。
2.可达性类
欲了解更多信息,请参阅可达性 (Apple Developer)。
使用http://huytd.github.io/datatify/ 。 这比添加库和自己编写代码更容易。
第一 :在框架中添加CFNetwork.framework
代码 : ViewController.m
#import "Reachability.h" - (void)viewWillAppear:(BOOL)animated { Reachability *r = [Reachability reachabilityWithHostName:@"www.google.com"]; NetworkStatus internetStatus = [r currentReachabilityStatus]; if ((internetStatus != ReachableViaWiFi) && (internetStatus != ReachableViaWWAN)) { /// Create an alert if connection doesn't work UIAlertView *myAlert = [[UIAlertView alloc]initWithTitle:@"No Internet Connection" message:NSLocalizedString(@"InternetMessage", nil)delegate:nil cancelButtonTitle:@"Ok" otherButtonTitles:nil]; [myAlert show]; [myAlert release]; } else { NSLog(@"INTERNET IS CONNECT"); } }
首先下载可达性类,并把reachability.h和reachabilty.m文件放到你的Xcode中 。
最好的方法是制作一个通用的函数类(NSObject),以便您可以使用它的任何类。 这些是networking连接可达性检查的两种方法:
+(BOOL) reachabiltyCheck { NSLog(@"reachabiltyCheck"); BOOL status =YES; [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(reachabilityChanged:) name:kReachabilityChangedNotification object:nil]; Reachability * reach = [Reachability reachabilityForInternetConnection]; NSLog(@"status : %d",[reach currentReachabilityStatus]); if([reach currentReachabilityStatus]==0) { status = NO; NSLog(@"network not connected"); } reach.reachableBlock = ^(Reachability * reachability) { dispatch_async(dispatch_get_main_queue(), ^{ }); }; reach.unreachableBlock = ^(Reachability * reachability) { dispatch_async(dispatch_get_main_queue(), ^{ }); }; [reach startNotifier]; return status; } +(BOOL)reachabilityChanged:(NSNotification*)note { BOOL status =YES; NSLog(@"reachabilityChanged"); Reachability * reach = [note object]; NetworkStatus netStatus = [reach currentReachabilityStatus]; switch (netStatus) { case NotReachable: { status = NO; NSLog(@"Not Reachable"); } break; default: { if (!isSyncingReportPulseFlag) { status = YES; isSyncingReportPulseFlag = TRUE; [DatabaseHandler checkForFailedReportStatusAndReSync]; } } break; } return status; } + (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 NO; } BOOL isReachable = flags & kSCNetworkFlagsReachable; BOOL needsConnection = flags & kSCNetworkFlagsConnectionRequired; BOOL nonWiFi = flags & kSCNetworkReachabilityFlagsTransientConnection; NSURL *testURL = [NSURL URLWithString:@"http://www.apple.com/"]; NSURLRequest *testRequest = [NSURLRequest requestWithURL:testURL cachePolicy:NSURLRequestReloadIgnoringLocalCacheData timeoutInterval:20.0]; NSURLConnection *testConnection = [[NSURLConnection alloc] initWithRequest:testRequest delegate:self]; return ((isReachable && !needsConnection) || nonWiFi) ? (testConnection ? YES : NO) : NO; }
现在你可以通过调用这个类方法来检查任何类的networking连接。
要做到这一点是非常简单的。 以下方法将起作用。 只要确保不允许使用名称传入诸如HTTP,HTTPS等的主机名协议。
-(BOOL)hasInternetConnection:(NSString*)urlAddress { SCNetworkReachabilityRef ref = SCNetworkReachabilityCreateWithName(kCFAllocatorDefault, [urlAddress UTF8String]); SCNetworkReachabilityFlags flags; if (!SCNetworkReachabilityGetFlags(ref, &flags)) { return NO; } return flags & kSCNetworkReachabilityFlagsReachable; }
这是快速简单,无痛。
我发现简单易用的SimplePingHelper库。
示例代码: chrishulbert / SimplePingHelper ( GitHub )
Reachability类可以确定互联网连接是否可用于设备…
但是在访问Intranet资源的情况下:
使用可达性类Ping内部网服务器始终返回true。
所以在这种情况下,一个快速的解决scheme是创build一个叫做pingme
的web方法以及服务上的其他webmethods。 pingme
应该返回一些东西。
所以我写了下面的常用函数的方法
-(BOOL)PingServiceServer { NSURL *url=[NSURL URLWithString:@"http://www.serveraddress/service.asmx/Ping"]; NSMutableURLRequest *urlReq=[NSMutableURLRequest requestWithURL:url]; [urlReq setTimeoutInterval:10]; NSURLResponse *response; NSError *error = nil; NSData *receivedData = [NSURLConnection sendSynchronousRequest:urlReq returningResponse:&response error:&error]; NSLog(@"receivedData:%@",receivedData); if (receivedData !=nil) { return YES; } else { NSLog(@"Data is null"); return NO; } }
上面的方法对我来说非常有用,所以每当我尝试发送一些数据到服务器时,我总是使用这个低超时URLRequest来检查我的Intranet资源的可达性。
我认为这是最好的答案。
"Yes" means connected. "No" means disconnected.
#import "Reachability.h" - (BOOL)canAccessInternet { Reachability *IsReachable = [Reachability reachabilityForInternetConnection]; NetworkStatus internetStats = [IsReachable currentReachabilityStatus]; if (internetStats == NotReachable) { return NO; } else { return YES; } }
-
Download the Reachability file, https://gist.github.com/darkseed/1182373
-
And add
CFNetwork.framework
and 'SystemConfiguration.framework' in framework -
Do #import "Reachability.h"
First : Add CFNetwork.framework
in framework
Code : ViewController.m
- (void)viewWillAppear:(BOOL)animated { Reachability *r = [Reachability reachabilityWithHostName:@"www.google.com"]; NetworkStatus internetStatus = [r currentReachabilityStatus]; if ((internetStatus != ReachableViaWiFi) && (internetStatus != ReachableViaWWAN)) { /// Create an alert if connection doesn't work UIAlertView *myAlert = [[UIAlertView alloc]initWithTitle:@"No Internet Connection" message:NSLocalizedString(@"InternetMessage", nil)delegate:nil cancelButtonTitle:@"Ok" otherButtonTitles:nil]; [myAlert show]; [myAlert release]; } else { NSLog(@"INTERNET IS CONNECT"); } }
Checking the Internet connection availability in (iOS) Xcode 8 , Swift 3.0
This is simple method for checking the network availability like our device is connected to any network or not. I have managed to translate it to Swift 3.0 and here the final code. The existing Apple Reachability class and other third party libraries seemed to be too complicated to translate to Swift.
This works for both 3G,4G and WiFi connections.
Don't forget to add “SystemConfiguration.framework” to your project builder.
//Create new swift class file Reachability in your project. import SystemConfiguration public class InternetReachability { class func isConnectedToNetwork() -> Bool { var zeroAddress = sockaddr_in(sin_len: 0, sin_family: 0, sin_port: 0, sin_addr: in_addr(s_addr: 0), sin_zero: (0, 0, 0, 0, 0, 0, 0, 0)) zeroAddress.sin_len = UInt8(sizeofValue(zeroAddress)) zeroAddress.sin_family = sa_family_t(AF_INET) let defaultRouteReachability = withUnsafePointer(&zeroAddress) { SCNetworkReachabilityCreateWithAddress(nil, UnsafePointer($0)).takeRetainedValue() } var flags: SCNetworkReachabilityFlags = 0 if SCNetworkReachabilityGetFlags(defaultRouteReachability, &flags) == 0 { return false } let isReachable = (flags & UInt32(kSCNetworkFlagsReachable)) != 0 let needsConnection = (flags & UInt32(kSCNetworkFlagsConnectionRequired)) != 0 return isReachable && !needsConnection } } // Check network connectivity from anywhere in project by using this code. if InternetReachability.isConnectedToNetwork() == true { print("Internet connection OK") } else { print("Internet connection FAILED") }
Import Reachable.h
class in your ViewController
, and use the following code to check connectivity :
#define hasInternetConnection [[Reachability reachabilityForInternetConnection] isReachable] if (hasInternetConnection){ // To-do block }
There is also another method to check Internet connection using the iPhone SDK.
Try to implement the following code for the network connection.
#import <SystemConfiguration/SystemConfiguration.h> #include <netdb.h> /** Checking for network availability. It returns YES if the network is available. */ + (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) { printf("Error. Could not recover network reachability flags\n"); return NO; } BOOL isReachable = ((flags & kSCNetworkFlagsReachable) != 0); BOOL needsConnection = ((flags & kSCNetworkFlagsConnectionRequired) != 0); return (isReachable && !needsConnection) ? YES : NO; }
Apart from reachability you may also use the Simple Ping helper library . It works really nice and is simple to integrate.
- Step 1: Add the Reachability class in your Project.
- Step 2: Import the Reachability class
-
Step 3: Create the below function
- (BOOL)checkNetConnection { self.internetReachability = [Reachability reachabilityForInternetConnection]; [self.internetReachability startNotifier]; NetworkStatus netStatus = [self.internetReachability currentReachabilityStatus]; switch (netStatus) { case NotReachable: { return NO; } case ReachableViaWWAN: { return YES; } case ReachableViaWiFi: { return YES; } } }
-
Step 4: Call the function as below:
if (![self checkNetConnection]) { [GlobalFunctions showAlert:@"" message:@"Please connect to the Internet!" canBtntitle:nil otherBtnTitle:@"Ok"]; return; } else { Log.v("internet is connected","ok"); }