在我的应用程序委托中,我有这个:
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。