即使我们确实有互联网连接,可达性有时也会失败 [英] Reachability sometimes fails, even when we do have an internet connection
问题描述
我已经搜索过但看不到类似的问题。
I've searched but can't see a similar question.
我已根据可达性示例添加了一种检查互联网连接的方法。它大部分时间都可以工作,但是当安装在iPhone上时,即使我有互联网连接也常常会失败(只有当使用3G / EDGE时 - WiFi就可以了)。
I've added a method to check for an internet connection per the Reachability example. It works most of the time, but when installed on the iPhone, it quite often fails even when I do have internet connectivity (only when on 3G/EDGE - WiFi is OK).
基本上下面的代码返回NO。
Basically the code below returns NO.
如果我切换到另一个应用程序,比如Mail或Safari,然后连接,然后切换回应用程序,然后代码说互联网是可以访问的。有点似乎需要'轻推'。
If I switch to another app, say Mail or Safari, and connect, then switch back to the app, then the code says the internet is reachable. Kinda seems like it needs a 'nudge'.
之前有人见过这个吗?有什么想法?
Anyone seen this before? Any ideas?
非常感谢
James
Many thanks James
+ (BOOL) doWeHaveInternetConnection{
BOOL success;
// google should always be up right?!
const char *host_name = [@"google.com" cStringUsingEncoding:NSASCIIStringEncoding];
SCNetworkReachabilityRef reachability = SCNetworkReachabilityCreateWithName(NULL,
host_name);
SCNetworkReachabilityFlags flags;
success = SCNetworkReachabilityGetFlags(reachability, &flags);
BOOL isAvailable = success && (flags & kSCNetworkFlagsReachable) && !(flags & kSCNetworkFlagsConnectionRequired);
if (isAvailable) {
NSLog(@"Google is reachable: %d", flags);
}else{
NSLog(@"Google is unreachable");
}
return isAvailable;
}
推荐答案
看起来你已经从Apple示例代码中删除了一些基本的可访问性代码。当你完好无损地执行此操作会发生什么?
Looks like you've stripped out some basic reachability code from the Apple example code. What happens when you leave it intact and do this?
Reachability *hostReach = [[Reachability reachabilityWithHostName: @"www.apple.com"] retain];
NetworkStatus netStatus = [hostReach currentReachabilityStatus];
if (netStatus == NotReachable)
{
NSLog(@"NotReachable");
}
if (netStatus == ReachableViaWiFi)
{
NSLog(@"ReachableViaWiFi");
}
if (netStatus == ReachableViaWWAN)
{
NSLog(@"ReachableViaWWAN");
}
这篇关于即使我们确实有互联网连接,可达性有时也会失败的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!