我正在使用AFNetworking
,并且想知道如何在用户连接到没有有效互联网连接的无线网络时检测场景。
我重现了这种情况,在没有连接dsl线路的情况下为路由器供电。
AFNetworking return AFNetworkReachabilityStatusReachableViaWiFi = 2
我的代码:
[[AFNetworkReachabilityManager sharedManager] setReachabilityStatusChangeBlock:^(AFNetworkReachabilityStatus status) {
NSLog(@"Reachability: %@", AFStringFromNetworkReachabilityStatus(status));
self.isInternetAvialable = status > 0;
}];
感谢
我将代码重新命名为
AFNetworkReachabilityManager* manager = [AFNetworkReachabilityManager managerForDomain:@"http://www.google.com"];
[manager setReachabilityStatusChangeBlock:^(AFNetworkReachabilityStatus status) {
NSLog(@"Reachability: %@", AFStringFromNetworkReachabilityStatus(status));
self.isInternetAvialable = status > 0;
}];
[manager startMonitoring];
现在该块永远不会被调用!
答案 0 :(得分:2)
您可以使用[AFNetworkReachabilityManager sharedManager]
并传递适当的主机名,而不是使用仅监控网络连接的[AFNetworkReachabilityManager managerForDomain:(NSString *)domain]
,例如" www.google.com" - 通过这种方式,您可以测试您所连接的网络是否具有Internet访问权限 - 它仍然可以被本地DNS和Web服务器欺骗,但我认为不太可能有人这样做。
获得AFNetworkReachabilityManager
后,可以像对共享管理器一样设置更改块
答案 1 :(得分:1)
使用Reachability类及其reachabilityForInternetConnection
方法。
Reachability *networkReachability = [Reachability reachabilityForInternetConnection];
NetworkStatus networkStatus = [networkReachability currentReachabilityStatus];
if (networkStatus == NotReachable)
{
NSLog(@"There is NO Internet connection");
}
else
{
NSLog(@"There is Internet connection");
}
答案 2 :(得分:0)
通过Apple的Reachability课程。它具有您需要的所有功能。这里最好的选择是使用域名(如谷歌)来检查实际的互联网连接。
汇总示例代码:
在didFinishLaunchingWithOptions:
[[NSNotificationCenter defaultCenter] addObserver:self
selector:@selector(checkNetworkStatus:)
name:kReachabilityChangedNotification
object:nil];
internetReachable = [[Reachability reachabilityForInternetConnection] retain];
[internetReachable startNotifier];
// check if a pathway to a random host exists
hostReachable = [Reachability reachabilityWithHostname:@"SOME_HOST"];
[hostReachable startNotifier];
然后,在目标方法中:
- (void) checkNetworkStatus:(NSNotification *)notice {
NetworkStatus internetStatus = [internetReachable currentReachabilityStatus];
switch (internetStatus)
{
case NotReachable:
{
NSLog(@"The internet is down.");
break;
}
case ReachableViaWiFi:
{
NSLog(@"The internet is working via WIFI.");
break;
}
case ReachableViaWWAN:
{
NSLog(@"The internet is working via WWAN.");
break;
}
}
NetworkStatus hostStatus = [hostReachable currentReachabilityStatus];
switch (hostStatus)
{
case NotReachable:
{
NSLog(@"A gateway to the host server is down.");
break;
}
case ReachableViaWiFi:
{
NSLog(@"A gateway to the host server is working via WIFI.");
break;
}
case ReachableViaWWAN:
{
NSLog(@"A gateway to the host server is working via WWAN.");
break;
}
}
}