How to check for an active Internet connection on iOS or macOS?
我想检查一下我是否在使用CocoaTouch库的iOS或使用CocoaLibraries的MacOS上有互联网连接。
我想出了一个方法,用一个
1 2 3 4 5 | - (BOOL) connectedToInternet { NSString *URLString = [NSString stringWithContentsOfURL:[NSURL URLWithString:@"http://www.google.com"]]; return ( URLString != NULL ) ? YES : NO; } |
我所做的是不是很糟糕(更不用说iOS 3.0和MacOS 10.4中不赞成使用
重要事项:此检查应始终异步执行。下面的大多数答案是同步的,所以要小心,否则你会冻结你的应用程序。
迅捷1)通过cocoapods或carthage安装:https://github.com/ashleymills/reachability.swift
2)通过闭包测试可达性
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 | let reachability = Reachability()! reachability.whenReachable = { reachability in if reachability.connection == .wifi { print("Reachable via WiFi") } else { print("Reachable via Cellular") } } reachability.whenUnreachable = { _ in print("Not reachable") } do { try reachability.startNotifier() } catch { print("Unable to start notifier") } |
Objtovi-C
1)在项目中添加EDOCX1[0]框架,但不要担心将其包含在任何地方。
2)在项目中添加Tony百万版的
3)更新接口部分
1 2 3 4 5 6 7 8 | #import"Reachability.h" // Add this to the interface in the .m file of your view controller @interface MyViewController () { Reachability *internetReachableFoo; } @end |
4)然后在视图控制器的.m文件中实现此方法,您可以调用该文件
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 | // 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]; } |
重要提示:
注意:您使用的域并不重要。它只是测试任何域的网关。
我喜欢保持简单。我这样做的方式是:
1 2 3 4 5 6 7 8 9 10 11 12 13 | //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; } |
然后,每当我想查看是否有连接时,我都使用这个:
1 2 3 4 5 | if (![self connected]) { // Not connected } else { // Connected. Do some Internet stuff } |
此方法不等待更改的网络状态来完成任务。它只是在您请求时测试状态。
使用苹果的可访问性代码,我创建了一个函数,可以在不包含任何类的情况下正确地检查它。
在项目中包含SystemConfiguration.Framework。
进行一些导入:
1 2 3 | #import <sys/socket.h> #import <netinet/in.h> #import <SystemConfiguration/SystemConfiguration.h> |
现在只需调用此函数:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 | /* 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。
这以前是正确的答案,但现在已经过时了,因为您应该订阅通知以获得可访问性。此方法同步检查:
你可以使用苹果的可达性类。它还允许您检查是否启用了Wi-Fi:
1 2 3 4 5 6 7 | 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) { } |
可访问性类不是随SDK一起提供的,而是此Apple示例应用程序的一部分。只需下载它,并将reachability.h/m复制到您的项目中。此外,还必须将系统配置框架添加到项目中。
下面是一个非常简单的答案:
1 2 3 4 5 6 | 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应该指向一个非常小的网站。我在这里使用谷歌的移动网站,但是如果我有一个可靠的网络服务器,我会上传一个只有一个字符的小文件,以获得最大的速度。
如果你想做的就是检查设备是否以某种方式连接到互联网,我绝对推荐使用这个简单的解决方案。如果您需要知道用户是如何连接的,那么使用可到达性是一种方法。
小心:这会在加载网站时短暂地阻塞线程。在我的例子中,这不是问题,但你应该考虑这个(布拉德指出了这一点)。
以下是我在我的应用程序中如何做到的:虽然200状态响应代码不能保证任何东西,但它对我来说足够稳定。这不需要像这里发布的nsdata答案那样多的加载,因为我的只是检查头部响应。
银行代码1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 | func checkInternet(flag:Bool, completionHandler:(internet:Bool) -> Void) { UIApplication.sharedApplication().networkActivityIndicatorVisible = true let url = NSURL(string:"http://www.google.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 Google URL reachable } else { // No"Internet" aka Google URL un-reachable } }) } |
目标C代码
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 | typedef void(^connection)(BOOL); - (void)checkInternet:(connection)block { NSURL *url = [NSURL URLWithString:@"http://www.google.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 Google URL reachable } else { // No"Internet" aka Google URL un-reachable } }]; } |
苹果提供了样本代码来检查不同类型的网络可用性。另外,iPhone开发者食谱中也有一个例子。
注:请参见@khg关于苹果可访问性代码使用的回答意见。
你可以使用
1 2 3 4 5 6 7 | #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. |
苹果提供了一个示例应用程序,它可以做到这一点:
可达性
只更新了可到达性类。现在可以使用:
1 2 3 4 5 6 | 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,使用可到达性的现代化:
可达性
如果您使用的是
使用
使用这种方法的一个优点是,当可达性状态改变时,可以使用
1 2 3 4 5 6 7 8 9 10 11 12 | BKHTTPClient *httpClient = [BKHTTPClient sharedClient]; [httpClient setReachabilityStatusChangeBlock:^(AFNetworkReachabilityStatus status) { if (status == AFNetworkReachabilityStatusNotReachable) { // Not reachable } else { // Reachable } }]; |
您还可以使用
我在这个讨论中使用了代码,它看起来工作得很好(阅读整个线程!).
我还没有用所有可能的连接(比如特别的Wi-Fi)来全面测试它。
非常简单……尝试以下步骤:
步骤1:将
步骤2:将以下代码导入您的
1 | #import <SystemConfiguration/SystemConfiguration.h> |
步骤3:使用以下方法
类型1:
1
2
3
4
5
6
7
8
9
10
11
12
13- (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;
}
类型2:
进口抬头:
#import"Reachability.h" 。1
2
3
4
5
6- (BOOL)currentNetworkStatus
{
Reachability *reachability = [Reachability reachabilityForInternetConnection];
NetworkStatus networkStatus = [reachability currentReachabilityStatus];
return networkStatus != NotReachable;
}
步骤4:如何使用:
1 2 3 4 5 6 7 8 9 10 11 12 | - (void)CheckInternet { BOOL network = [self currentNetworkStatus]; if (network) { NSLog(@"Network Available"); } else { NSLog(@"No Network Available"); } } |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 | -(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; } } |
1 2 3 4 5 6 | - (void)viewWillAppear:(BOOL)animated { NSString *URL = [NSString stringWithContentsOfURL:[NSURL URLWithString:@"http://www.google.com"]]; return (URL != NULL ) ? YES : NO; } |
或者使用可达性类。
使用iPhone SDK检查互联网可用性有两种方法:
1。检查Google页面是否打开。
2。可达性类
有关更多信息,请参阅可达性(Apple Developer)。
第一:在框架中增加
代码:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 | #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"); } } |
使用http://huytd.github.io/datatify/。这比自己添加库和编写代码容易。
我发现使用库SimplePingHelper既简单又容易。
示例代码:Chrishulbert/SimplePingHelper(Github)
你自己做这件事非常简单。以下方法有效。只需确保不允许将主机名协议(如http、https等)与名称一起传入。
1 2 3 4 5 6 7 8 9 10 | -(BOOL)hasInternetConnection:(NSString*)urlAddress { SCNetworkReachabilityRef ref = SCNetworkReachabilityCreateWithName(kCFAllocatorDefault, [urlAddress UTF8String]); SCNetworkReachabilityFlags flags; if (!SCNetworkReachabilityGetFlags(ref, &flags)) { return NO; } return flags & kSCNetworkReachabilityFlagsReachable; } |
它快速简单,无痛。
还有另一种使用iPhone SDK检查互联网连接的方法。
尝试为网络连接实现以下代码。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 | #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 "); return NO; } BOOL isReachable = ((flags & kSCNetworkFlagsReachable) != 0); BOOL needsConnection = ((flags & kSCNetworkFlagsConnectionRequired) != 0); return (isReachable && !needsConnection) ? YES : NO; } |
下载可访问性文件,https://gist.github.com/darkseed/1182373
在框架中添加
do导入"reachability.h"
< BR>
第一:在框架中增加
代码:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 | - (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类,并将reachability.h和reachability.m文件放在Xcode中。
最好的方法是创建一个公共函数类(nsObject),以便您可以使用它的任何类。网络连接可访问性检查有两种方法:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 | +(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; } |
现在您可以通过调用这个类方法来检查任何类中的网络连接。
除了可访问性之外,您还可以使用简单的ping助手库。它工作得很好,集成起来也很简单。
可到达性类可以确定Internet连接是否可用于设备…
但在访问内部网资源时:
使用可访问性类Ping Intranet服务器始终返回true。
因此,在这种情况下,一个快速的解决方案是创建一个名为
所以我写了下面关于公共函数的方法
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 | -(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; } } |
上面的方法对我非常有用,所以每当我试图向服务器发送一些数据时,我总是使用这个低超时的url请求检查我的Intranet资源的可访问性。
我认为这是最好的答案。
"是"表示已连接。否"表示断开连接。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 | #import"Reachability.h" - (BOOL)canAccessInternet { Reachability *IsReachable = [Reachability reachabilityForInternetConnection]; NetworkStatus internetStats = [IsReachable currentReachabilityStatus]; if (internetStats == NotReachable) { return NO; } else { return YES; } } |
导入
1 2 3 4 | #define hasInternetConnection [[Reachability reachabilityForInternetConnection] isReachable] if (hasInternetConnection){ // To-do block } |
- 步骤1:在项目中添加可达性类。
- 步骤2:导入可达性类
步骤3:创建以下函数
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21- (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;
}
}
}步骤4:调用函数如下:
1
2
3
4
5
6
7
8
9
10
11if (![self checkNetConnection]) {
[GlobalFunctions showAlert:@""
message:@"Please connect to the Internet!"
canBtntitle:nil
otherBtnTitle:@"Ok"];
return;
}
else
{
Log.v("internet is connected","ok");
}
检查(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.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 | //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") } |
斯威夫特3/斯威夫特4
必须先导入
1 | import SystemConfiguration |
您可以使用以下方法检查Internet连接
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 | func isConnectedToNetwork() -> Bool { var zeroAddress = sockaddr_in() zeroAddress.sin_len = UInt8(MemoryLayout.size(ofValue: zeroAddress)) zeroAddress.sin_family = sa_family_t(AF_INET) let defaultRouteReachability = withUnsafePointer(to: &zeroAddress) { $0.withMemoryRebound(to: sockaddr.self, capacity: 1) {zeroSockAddress in SCNetworkReachabilityCreateWithAddress(nil, zeroSockAddress) } } var flags = SCNetworkReachabilityFlags() if !SCNetworkReachabilityGetFlags(defaultRouteReachability!, &flags) { return false } let isReachable = (flags.rawValue & UInt32(kSCNetworkFlagsReachable)) != 0 let needsConnection = (flags.rawValue & UInt32(kSCNetworkFlagsConnectionRequired)) != 0 return (isReachable && !needsConnection) } |
导入"reachability.h"
1 2 3 4 5 | -(BOOL)netStat { Reachability *test = [Reachability reachabilityForInternetConnection]; return [test isReachable]; } |
创建
1 2 3 4 5 6 7 8 9 10 11 12 13 | self.reachabilityManager = [AFNetworkReachabilityManager managerForDomain:@"yourDomain"]; [self.reachabilityManager startMonitoring]; [self.reachabilityManager setReachabilityStatusChangeBlock:^(AFNetworkReachabilityStatus status) { switch (status) { case AFNetworkReachabilityStatusReachableViaWWAN: case AFNetworkReachabilityStatusReachableViaWiFi: break; case AFNetworkReachabilityStatusNotReachable: break; default: break; } }]; |
从https://github.com/tonymillion/reachability获取reachability类,在项目中添加系统配置框架,在类中导入reachability.h,实现如下自定义方法:
1 2 3 4 5 6 7 | - (BOOL)isConnectedToInternet { //return NO; // Force for offline testing Reachability *hostReach = [Reachability reachabilityForInternetConnection]; NetworkStatus netStatus = [hostReach currentReachabilityStatus]; return !(netStatus == NotReachable); } |
这是针对Swift 3.0和Async的。大多数答案都是同步解决方案,如果连接速度很慢,它会阻塞您的主线程。这个解决方案更好,但并不完美,因为它依赖于谷歌来检查连接,所以可以随意使用其他URL。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 | func checkInternetConnection(completionHandler:@escaping (Bool) -> Void) { if let url = URL(string:"http://www.google.com/") { var request = URLRequest(url: url) request.httpMethod ="HEAD" request.cachePolicy = .reloadIgnoringLocalAndRemoteCacheData request.timeoutInterval = 5 let tast = URLSession.shared.dataTask(with: request, completionHandler: { (data, response, error) in completionHandler(error == nil) }) tast.resume() } else { completionHandler(true) } } |
使用xcode 9&swift 4.0检查(iOS)中的互联网连接可用性
遵循以下步骤
步骤1:创建一个扩展文件,并将其命名为:reachabilitymanager.swift,然后在下面添加代码行。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 | import Foundation import SystemConfiguration public class ConnectionCheck { class func isConnectedToNetwork() -> Bool { var zeroAddress = sockaddr_in() zeroAddress.sin_len = UInt8(MemoryLayout<sockaddr_in>.size) zeroAddress.sin_family = sa_family_t(AF_INET) guard let defaultRouteReachability = withUnsafePointer(to: &zeroAddress, { $0.withMemoryRebound(to: sockaddr.self, capacity: 1) { SCNetworkReachabilityCreateWithAddress(nil, $0) } }) else { return false } var flags: SCNetworkReachabilityFlags = [] if !SCNetworkReachabilityGetFlags(defaultRouteReachability, &flags) { return false } let isReachable = flags.contains(.reachable) let needsConnection = flags.contains(.connectionRequired) return (isReachable && !needsConnection) } } |
步骤2:使用下面的代码调用上面的扩展。
1 2 3 4 5 6 7 8 9 | if ConnectionCheck.isConnectedToNetwork() { print("Connected") //Online related Business logic } else{ print("disConnected") // offline related business logic } |
1 2 3 4 5 | Pod `Alamofire` has `NetworkReachabilityManager`, you just have to create one function func isConnectedToInternet() ->Bool { return NetworkReachabilityManager()!.isReachable } |
对于我的iOS项目,我建议使用
Reachability Class
以SWIFT声明。对我来说,它很好用
Wi-Fi and Cellular data
.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 | import SystemConfiguration public class Reachability { 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(MemoryLayout.size(ofValue: zeroAddress)) zeroAddress.sin_family = sa_family_t(AF_INET) let defaultRouteReachability = withUnsafePointer(to: &zeroAddress) { $0.withMemoryRebound(to: sockaddr.self, capacity: 1) {zeroSockAddress in SCNetworkReachabilityCreateWithAddress(nil, zeroSockAddress) } } var flags: SCNetworkReachabilityFlags = SCNetworkReachabilityFlags(rawValue: 0) if SCNetworkReachabilityGetFlags(defaultRouteReachability!, &flags) == false { return false } let isReachable = (flags.rawValue & UInt32(kSCNetworkFlagsReachable)) != 0 let needsConnection = (flags.rawValue & UInt32(kSCNetworkFlagsConnectionRequired)) != 0 let ret = (isReachable && !needsConnection) return ret } } |
使用条件语句,
1 2 3 4 5 6 7 | if Reachability.isConnectedToNetwork(){ * Enter Your Code Here* } } else{ print("NO Internet connection") } |
这个类在应用程序使用互联网连接的几乎所有情况下都很有用。例如,如果条件为真,则可以调用API或执行任务。
阿拉莫
我知道这个问题是在寻求Coca Touch解决方案,但我想为那些在iOS上搜索并检查互联网连接的人提供一个解决方案,在这里还有一个选择。
如果你已经在使用Alamoire,这里是你可以从中受益的地方。
您可以将以下类添加到您的应用程序中,并调用
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 | #import Alamofire class MNNetworkUtils { static let main = MNNetworkUtils() init() { manager = NetworkReachabilityManager(host:"google.com") listenForReachability() } private let manager: NetworkReachabilityManager? private var reachable: Bool = false private func listenForReachability() { self.manager?.listener = { [unowned self] status in switch status { case .notReachable: self.reachable = false case .reachable(_), .unknown: self.reachable = true } } self.manager?.startListening() } func isConnected() -> Bool { return reachable } } |
这是一个单人班级。每次当用户连接或断开网络时,它都会正确地将
此外,为了监控可访问性,您需要提供一个主机,目前我正在使用google.com,如果需要,请随意更改为任何其他主机或您的主机之一。将类名和文件名更改为与项目匹配的任何内容。
见
试试这个:
1 2 3 4 5 6 7 8 9 | - (void) connection:(NSURLConnection *)connection didFailWithError:(NSError *)error if ([self.delegate respondsToSelector:@selector(getErrorResponse:)]) { [self.delegate performSelector:@selector(getErrorResponse:) withObject:@"No Network Connection"]; } UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:@"BMC" message:@"No Network Connection" delegate:self cancelButtonTitle:nil otherButtonTitles:@"OK",nil]; [alertView show]; |
}