如何检查互联网工作与否在ios中
我试图检测互联网是否在使用AFNetworking
的设备上工作; 在这里提到SO AFNetworking 2.0可达性的答案。 我能够检测到设备连接WiFi或3G ..
问题是其实互联网是不是像WIFI上工作,但互联网不工作。
我如何检测互联网正在工作。就像我们检查使用ping …
我正在检查使用以下
-(BOOL)connected { __block BOOL reachable; // Setting block doesn't means you area running it right now [[AFNetworkReachabilityManager sharedManager] setReachabilityStatusChangeBlock:^(AFNetworkReachabilityStatus status) { switch (status) { case AFNetworkReachabilityStatusNotReachable: NSLog(@"No Internet Connection"); reachable = NO; break; case AFNetworkReachabilityStatusReachableViaWiFi: NSLog(@"WIFI"); reachable = YES; break; case AFNetworkReachabilityStatusReachableViaWWAN: NSLog(@"3G"); reachable = YES; break; default: NSLog(@"Unkown network status"); reachable = NO; break; } }]; // and now activate monitoring [[AFNetworkReachabilityManager sharedManager] startMonitoring]; return reachable;
}
添加通知观察员以更改networking状态。 就像在完成启动类下的应用程序委托类中添加以下代码一样
[[AFNetworkReachabilityManager sharedManager] startMonitoring]; [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(receiveNetworkChnageNotification:) name:AFNetworkingReachabilityDidChangeNotification object:nil];
在.h文件中添加全局警报视图。 因为它会在networking状态变化时出现和消失。
这里是通知函数调用:
- (void)receiveNetworkChnageNotification:(NSNotification *)notification { if (![self isReachable]) { self.alertView = [[UIAlertView alloc] initWithTitle:@"No Internet Connection" message:@"You have no internet connection on your device, please check and try again later." delegate:nil cancelButtonTitle:@"Cancel" otherButtonTitles:nil]; [self.alertView show]; } else { [self.alertView dismissWithClickedButtonIndex:0 animated:YES]; } }
您可以使用Reachability来确定您是否有连接到networking的function。 但是,如果您确实需要确定您有一个可行的互联网连接,那么最好的方法是尝试build立一个实际的连接并检查结果。 为此使用NSURLConnection。
NSURLRequest *theRequest=[NSURLRequest requestWithURL:[NSURL URLWithString:@"http://www.apple.com/"] cachePolicy:NSURLRequestUseProtocolCachePolicy timeoutInterval:60.0]; NSMutableData *receivedData = [NSMutableData dataWithCapacity:0]; NSURLConnection *theConnection=[[NSURLConnection alloc] initWithRequest:theRequest delegate:self]; if(!theConnection) { // Something went wrong. receivedData = nil; }
要确定您是否build立了可行的连接,请使用委托方法检查连接的结果:
-(void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error { NSLog(@"Connection failed! Error - %@ %@", [error localizedDescription], [[error userInfo] objectForKey:NSURLErrorFailingURLStringErrorKey]); }
- AFHTTPSessionManager头
- AFNetworking 2.0中的enqueueHTTPRequestOperation的替代方法
- 设备处于脱机状态时AFNetworking 2.0队列请求使用setReachabilityStatusChangeBlock执行任何操作
- 如何在AFnetworking中的AFHTTPRequestOperationManager请求中返回
- 获取请求失败:发布参数时无法接受(406)
- 在Swift中使用AFNetworking接收响应
- 使用AFNetworking 2.0上传图像
- 如何使用AFNetworking 2.0通过Rest API注册?
- 使用AFNetworking加载离线caching的JSON