需要一些Reachability帮助(2.0.3ddg)

时间:2010-01-28 17:04:49

标签: iphone objective-c reachability

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

我可以确认我实际上正在建立互联网连接,因为在applicationDidFinishLaunching之后,会有一个通知然后记录“ReachableViaWiFi”..

我做错了什么?为什么不立即确认有效的互联网连接?

- (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;
        }
    }
}

3 个答案:

答案 0 :(得分: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];
}

答案 1 :(得分:2)

Reachability示例代码为您提供异步回调/通知,以通知您可达性如何/何时发生变化。为了使您的代码有效,您应该按如下方式修改代码:

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

 // setup reachability
    [self setupReachability];
 }

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

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

答案 2 :(得分:1)

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