3

当我的应用程序启动时,我会检查可访问性,因为我需要立即连接互联网。不过,我的问题是,似乎没有立即确认NetworkStatus,这意味着在设置可达性之后,我检查是否有连接,然后返回没有连接,无论我是否真的在 WiFi 上/3G,或已关闭无线电。

我可以确认我实际上正在获得 Internet 连接,因为在 applicationDidFinishLaunching 之后立即有一个通知,然后记录“ReachableViaWiFi”..

我究竟做错了什么?为什么它没有立即确认有效的 Internet 连接?

- (void)applicationDidFinishLaunching:(UIApplication *)application {    
    NetworkStatus netStatus = [hostReach currentReachabilityStatus];
    if (netStatus == NotReachable) {
        ErrorViewController *errorViewController = [[ErrorViewController alloc] initWithNibName:@"ErrorView" bundle:[NSBundle mainBundle]];
        [tabBarController.view removeFromSuperview];
        [window addSubview:[errorViewController view]];
        return;
    }
}

-(void)setupReachability {
    [[NSNotificationCenter defaultCenter] addObserver: self selector: @selector(reachabilityChanged:) name:kReachabilityChangedNotification object: nil];
    hostReach = [[Reachability reachabilityWithHostName:@"www.google.com"] retain];
    [hostReach startNotifier];
}

-(void)reachabilityChanged:(NSNotification *)notification {
    Reachability* curReach = [notification object];
    NSParameterAssert([curReach isKindOfClass: [Reachability class]]);
    NetworkStatus netStatus = [curReach currentReachabilityStatus];
    BOOL connectionRequired = [curReach connectionRequired];
    switch (netStatus)
    {
        case NotReachable:
        {
            [[NSUserDefaults standardUserDefaults] setInteger:kNOTREACHABLE forKey:kREACHABILITYSTATUS];
            NSLog(@"NotReachable");
            connectionRequired = NO;  
            break;
        }

        case ReachableViaWWAN:
        {
            [[NSUserDefaults standardUserDefaults] setInteger:kREACHABLEVIAWWAN forKey:kREACHABILITYSTATUS];
            NSLog(@"ReachableViaWWAN");
            break;
        }
        case ReachableViaWiFi:
        {
            [[NSUserDefaults standardUserDefaults] setInteger:kNOTREACHABLE forKey:kREACHABILITYSTATUS];
            NSLog(@"ReachableViaWiFi");
            break;
        }
    }
}
4

3 回答 3

4

好的,所以在我自己尝试了一些东西之后,我通过添加一行额外的代码实际上让它工作了:

-(void)setupReachability {
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(reachabilityChanged:) name:kReachabilityChangedNotificationV2 object:nil];
    hostReach = [[ReachabilityV2 reachabilityWithHostName:@"www.google.com"] retain];
    [hostReach connectionRequired]; // this line was added, and apparently forces a connection requirement..
    [hostReach startNotifier];
}
于 2010-01-28T20:52:44.290 回答
2

可达性示例代码为您提供异步回调/通知,以通知您可达性如何/何时更改。为了使您的代码正常工作,您应该按如下方式修改您的代码:

- (void) applicationDidFinishLaunching:(UIApplication *)application {

 // setup reachability
    [self setupReachability];
 }

然后在您的回调中,当您收到通知时,您会根据应用程序的需要做出反应。

换句话说,您不能立即检查applicationDidFinishLaunching(). 如果你想这样做,那么你必须使用同步/阻塞方法,例如你可以使用我对这个问题的回答中提供的代码。

于 2010-01-28T17:27:06.680 回答
1

您必须将 hostReach 作为类级别变量。

于 2011-03-29T12:43:16.900 回答