我正在努力獲得真實的互聯網連接狀態。我已經使用蘋果的可達性,但它只給我的WiFi連接狀態,即不包括設備通過WiFi連接(到路由器或熱點),但無線路由器或熱點本身沒有連接到互聯網的情況。這種情況可以通過從wifi路由器拉出互聯網輸入電纜來重現。對於reachabilityForInternetConnection
和ReachabilityWithHostName
,可達性的通知程序均返回ReachableViaWiFi
。我很解決這個問題。我也通過NSURLConnection
嘗試過,但這太耗電了,我個人不喜歡這種解決方案來繼續提供URL請求,儘管它在後臺線程中。如何檢測wifi資源丟失連接時互聯網可達性的損失?
下面是我使用的代碼(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];
然後在觀測方法:
- (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;
}
}
}
嗨@艾哈邁德。你有沒有找到解決這個問題的方法?我有完全相同的問題 - 我的用戶將他們的設備連接到Wifi熱點,當熱點失去連接時,應用程序不知道。 – 2015-11-18 01:01:23
2016年仍然沒有解決,得到同樣的問題。 – 2016-01-13 15:39:52