0

在我的应用程序委托中,我有这个:

Reachability* reach = [Reachability reachabilityWithHostname:@"www.google.com"];

[[NSNotificationCenter defaultCenter] addObserver:self 
                                         selector:@selector(reachabilityChanged:) 
                                             name:kReachabilityChangedNotification 
                                           object:nil];

[reach startNotifier];

HomeViewController_iPhone *homeViewController = [[HomeViewController_iPhone alloc] initWithNibName:@"HomeViewController_iPhone" bundle:nil];
homeViewController.managedObjectContext = self.managedObjectContext;
UINavigationController *homeNavController = [[UINavigationController alloc] initWithRootViewController: homeViewController];
homeNavController.navigationBar.barStyle = UIBarStyleBlackTranslucent;

self.tabBarController.viewControllers = [NSArray arrayWithObjects:homeNavController, nil];

...

-(void)reachabilityChanged:(NSNotification*)note
{
Reachability * reach = [note object];

if([reach isReachable])
{
    NSLog(@"Notification Says Reachable");
    self.isConnected = YES;
}
else
{
    NSLog(@"Notification Says UN-Reachable");
    self.isConnected = NO;
}
}

问题是在我的 HomeViewController (viewDidLoad) 我这样做:

AppDelegate *appDelegate = (AppDelegate*)[[UIApplication sharedApplication] delegate];

if (appDelegate.isConnected)
{
    dispatch_async(kBgQueue, ^{
        NSData* data = [NSData dataWithContentsOfURL: kFeedURL];
        [self performSelectorOnMainThread:@selector(fetchedData:) 
                               withObject:data waitUntilDone:YES];
    });
}

但 appDelegate.isConnected 始终为“否”,即使我有连接也是如此。我认为在 Reachability 类建立连接之前进行检查。但是我在哪里调用来获取数据呢?我已经尝试过 viewDidLoad 和 viewWillAppear,但在这两点上 isConnected 仍然是 NO。

4

1 回答 1

0

通过在创建视图控制器之前在应用程序委托中执行此操作来解决,如 dnstevenson 建议的答案。

Reachability *reachability = [Reachability reachabilityForInternetConnection];    
NetworkStatus internetStatus = [reachability currentReachabilityStatus];
if (internetStatus != NotReachable) {
    //my web-dependent code
}
else {
    //there-is-no-connection warning
}
于 2012-08-11T04:11:58.777 回答