Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
447 views
in Technique[技术] by (71.8m points)

iphone - Reachability sometimes fails, even when we do have an internet connection

I've searched but can't see a similar question.

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).

Basically the code below returns NO.

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?

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;

}

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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");
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...