0

I have an app that on the AppDelegate calls a SyncEngine. This kicks off a process of fetching data from parse.com and parsing that data into local objects and storing that info in a core data db on the device.

The app then loads a tabbarcontroller with 2 viewcontrollers:

1) a mapview controller 2) a tableview controller

The map view controller loads the core data data into an array and uses it to plot locations on a map. The tablevc takes that same data and puts it into cells.

Im trying to have the app check for internet connectivity and load the data depending on whether its fetched or local. Here is the deal:

viewDidLoad in mapVC it registers for a notification of when the data is completed loading (from the web). Once that happens, it calls loadResultsFromCoreData method which executes the CD fetch request. So if there is no internet connectivity, that notification will never be received.

My question is, when and where is the best place to check for internet connectivity? Im using this code in the AppDelegate so far but of course, its too early, so the BOOLs get set to NO:

- (BOOL) connectedToNetwork
{
    Reachability *r = [Reachability reachabilityWithHostName:@"www.google.com"];
    NetworkStatus internetStatus = [r currentReachabilityStatus];
    BOOL internet;
    if ((internetStatus != ReachableViaWiFi) && (internetStatus != ReachableViaWWAN)) {
        internet = NO;
    } else {
        internet = YES;
    }
    return internet;
}

-(BOOL) checkInternet
{
    //Make sure we have internet connectivity
    if([self connectedToNetwork] != YES) {
        UIAlertView *internetAlert = [[UIAlertView alloc] initWithTitle:@"Alert" message:@"Internet Required" delegate:self cancelButtonTitle:@"Cancel" otherButtonTitles:@"Ok", nil];
        [internetAlert show];
        return NO;
    } else {
        return YES;
    }
}

Any help :)

marciokoko
  • 4,988
  • 8
  • 51
  • 91

1 Answers1

1

I think the problem is with your connectedToNetwork method. ReachabilityWithHost needs time to connect to the specified site once created and you start polling it instantly. What you should probably do is register for status change notifications with the reachability object you create. There's an example in the Reachability example from Apple but the gist is this:

// Register to find out when reachability status changes
[[NSNotificationCenter defaultCenter] addObserver: self selector: @selector(<Whatever method you want to respond to reachability changes>) name: kReachabilityChangedNotification object: nil];

// Create a reachability object to start monitoring
Reachability* reach = [[Reachability reachabilityWithHostName: @"www.google.com"] retain];

// Start broadcasting status changes from the reachability object
[reach startNotifier];
Huhwha
  • 575
  • 5
  • 15