我正试图使用AFNetworking
检测互联网是否正常运行;在这里提到答案
AFNetworking 2.0 Reachability。我能够检测到设备是连接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;
}
答案 0 :(得分:1)
添加通知观察员以了解网络状态的变化。 就像在完成启动类
下的app delegate类中添加以下代码一样 [[AFNetworkReachabilityManager sharedManager] startMonitoring];
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(receiveNetworkChnageNotification:) name:AFNetworkingReachabilityDidChangeNotification object:nil];
在.h文件中添加全局警报视图。因为它会在网络状态变化时出现和消失。
这里是通知功能:
- (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];
}
}
答案 1 :(得分:0)
您可以使用“可访问性”来确定您是否具有到网络的功能连接。但是,如果您确实需要确定您有可行的互联网连接,那么最好的方法是尝试建立实际连接并检查结果。使用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;
}
要确定您是否建立了可行的连接,请使用委托方法检查连接的结果:
-(void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error
{
NSLog(@"Connection failed! Error - %@ %@", [error localizedDescription],
[[error userInfo] objectForKey:NSURLErrorFailingURLStringErrorKey]);
}