Ahm*_*med 8 iphone objective-c reachability ios
我正在努力获得真实的互联网连接状态.我已经使用了Apple的Reachability但它只给了我wifi连接的状态,即没有覆盖设备通过wifi连接(到路由器或热点)的情况,但wifi路由器或热点本身没有连接到互联网.通过从wifi路由器拉入互联网输入电缆可以重现这种情况.ReachableViaWiFi两个reachabilityForInternetConnection和的可达性通知程序返回ReachabilityWithHostName.我对这个问题非常感兴趣.我通过它尝试了它,NSURLConnection但是电池耗尽过多而且个人我不喜欢那种继续发出URL请求的解决方案,尽管在后台线程中.
这是我正在使用的代码(由SO老师提供,但不记得确切的链接)
[[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: @"www.google.com"] retain];
[hostReachable startNotifier];
Run Code Online (Sandbox Code Playgroud)
然后在观察者方法中:
- (void) checkNetworkStatus:(NSNotification *)notice{
// called after network status changes
NetworkStatus internetStatus = [internetReachable currentReachabilityStatus];
switch (internetStatus)
{
case NotReachable:
{
NSLog(@"The internet is down.");
self.isInternetReachable = NO;
break;
}
case ReachableViaWiFi:
{
NSLog(@"The internet is working via WIFI.");
self.isInternetReachable = YES;
break;
}
case ReachableViaWWAN:
{
NSLog(@"The internet is working via WWAN.");
self.isInternetReachable = YES;
break;
}
}
NetworkStatus hostStatus = [hostReachable currentReachabilityStatus];
switch (hostStatus)
{
case NotReachable:
{
NSLog(@"A gateway to the host server is down.");
self.isHostReachable = NO;
break;
}
case ReachableViaWiFi:
{
NSLog(@"A gateway to the host server is working via WIFI.");
self.isHostReachable = YES;
break;
}
case ReachableViaWWAN:
{
NSLog(@"A gateway to the host server is working via WWAN.");
self.isHostReachable = YES;
break;
}
}
}
Run Code Online (Sandbox Code Playgroud)
根据Reachability,它不仅检查wifi,还检查WWAN/3G并且没有互联网接入,为什么你认为除了WIFI之外它不检查?
typedef enum {
NotReachable = 0,
ReachableViaWiFi,
ReachableViaWWAN
} NetworkStatus;
Run Code Online (Sandbox Code Playgroud)
如果你想检查特定主机的可达性,那么你可以像这样自己设置主机
Reachability *hostReach = [Reachability reachabilityWithHostName: @"www.google.com"];
NetworkStatus netStatus = [hostReach currentReachabilityStatus];
switch (netStatus)
{
case ReachableViaWWAN:
{
NSLog(@"WWAN/3G");
break;
}
case ReachableViaWiFi:
{
NSLog(@"WIFI");
break;
}
case NotReachable:
{
NSLog(@"NO Internet");
break;
}
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
7210 次 |
| 最近记录: |