0

In my app delegate I have this:

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

The problem is that in my HomeViewController (viewDidLoad) I do this:

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];
    });
}

But appDelegate.isConnected is always NO, even when I have a connection. I think the check is being made before the Reachability class establishes that there is a connection. But where to I make the call to fetch the data? I've tried viewDidLoad and viewWillAppear, but isConnected is still NO at both of those points.

soleil
  • 12,133
  • 33
  • 112
  • 183
  • Also, the fetch works if I don't use the if (appDelegate.isConnected) statement, but i need to do that check because if the user doesn't have a connection the dispatch_async call will crash the app. – soleil Aug 09 '12 at 23:15
  • Perhaps this answer will help -> http://stackoverflow.com/questions/5195012/how-to-use-reachability-class-to-detect-valid-internet-connection?rq=1 – dnstevenson Aug 10 '12 at 00:28

1 Answers1

0

Solved by doing this in the app delegate, before creating the view controllers, as in the answer suggested by dnstevenson.

Reachability *reachability = [Reachability reachabilityForInternetConnection];    
NetworkStatus internetStatus = [reachability currentReachabilityStatus];
if (internetStatus != NotReachable) {
    //my web-dependent code
}
else {
    //there-is-no-connection warning
}
soleil
  • 12,133
  • 33
  • 112
  • 183