无法使用Reachability reachabilityForInternetConnection检测Internet连接

时间:2012-03-07 07:56:27

标签: objective-c ios connection reachability

我有问题。我正在使用可达性的reachabilityForInternetConnection方法来检测互联网可用性,但我没有获得连接状态而不是互联网状态。我的意思是,如果我打开我的Wifi连接,该方法给了我正确的指示,我没有连接但是如果wifi打开并且互联网连接不起作用,它似乎不起作用。有什么想法吗?

最好的问候

2 个答案:

答案 0 :(得分:3)

可达性仅可用于检测iPhone是否连接到互联网的网关。网关的背后是什么,它不会告诉你。如果局域网可以访问但你没有退出互联网怎么办? iPhone如何猜测它所看到的(局域网)不是整个互联网?

您应该向真实网站提出一些真实的请求。如果失败,则连接到Internet时会出现问题,并且通过可达性结果,您甚至可以了解问题所在。最简单的方法是使用NSUrlRequest向http://www.google.com发出请求。 (如果谷歌死了,你可能会认为那里有更大的问题,然后你的应用程序的连接:)

答案 1 :(得分:2)

我在我的应用中使用它:

// Check for internet connection
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(checkNetworkStatus:) name:kReachabilityChangedNotification object:nil];

internetReachable = [Reachability reachabilityForInternetConnection];
[internetReachable startNotifier];

// Check if a pathway to a random host exists
hostReachable = [Reachability reachabilityWithHostName: @"www.apple.com"];
[hostReachable startNotifier];

- (void) checkNetworkStatus:(NSNotification *)notice
{
    // Called after network status changes
    NetworkStatus internetStatus = [internetReachable currentReachabilityStatus];
    switch (internetStatus)
    {
            // Case: No internet
        case NotReachable:
        {
            internetActive = NO;

            // Switch to the NoConnection page
            NoConnectionViewController *notConnected = [[NoConnectionViewController alloc] initWithNibName:@"NoConnectionViewController" bundle:[NSBundle mainBundle]];

            notConnected.modalTransitionStyle = UIModalTransitionStyleFlipHorizontal;
            [self presentModalViewController:notConnected animated:NO];

            break;
        }
        case ReachableViaWiFi:
        {
            internetActive = YES;
            break;
        }
        case ReachableViaWWAN:
        {
            internetActive = YES;
            break;
        }
    }

    // Check if the host site is online
    NetworkStatus hostStatus = [hostReachable currentReachabilityStatus];
    switch (hostStatus)
    {
        case NotReachable:
        {
            hostActive = NO;
            break;
        }
        case ReachableViaWiFi:
        {
            hostActive = YES;
            break;
        }
        case ReachableViaWWAN:
        {
            hostActive = YES;
            break;
        }
    }
}