Search code examples
iphoneobjective-ciosreachability

Objective C - Using Reachability to constantly check for network connection during download


I am using this piece of code to check for a network connection within my application and, if a connection exists, pull data and display it:

 if([[Reachability reachabilityForInternetConnection] currentReachabilityStatus] == NotReachable) {
            errorView = [[UIAlertView alloc] 
                         initWithTitle: @"Network Error" 
                         message: @"No Network connection availible!" 
                         delegate: self 
                         cancelButtonTitle: @"OK" otherButtonTitles: nil]; 
            [errorView show];
        }
        else
        {
            HUD = [[MBProgressHUD alloc] initWithView:self.navigationController.view];
            [self.navigationController.view addSubview:HUD];

            HUD.delegate = self;
            HUD.labelText = @"Performing Initial Download";
            HUD.minSize = CGSizeMake(135.f, 135.f);

            [HUD showWhileExecuting:@selector(pullAndDisplayData) onTarget:self withObject:nil animated:YES];
        }

However, I would like to adapt this code so that it constantly checks for internet connection throughout the download process, and if I lose connection, to stop the download and display and appropriate alert message to the user. Can anyone advise as to how I may go about this?

Thanks,

Tysin


Solution

  • You need to add an observer for notification name

    kReachabilityChangedNotification
    

    and then call

    [[Reachability reachabilityForInternetConnection] startNotifier];
    

    When reachability changes, the notification will be posted, and then you can perform any actions you need.