Alertview not called when no Internet access

73 views Asked by At

Use the following standard calls to get data from a server - and standard Alert if there's an error - like no internet access. If I turn off the network the app crashes, never hitting the NSLog calls for *response or *error, never entering the alert.

dispatch_queue_t concurrentQueue =  dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);

//this will start the URL call and download in bg

dispatch_async(concurrentQueue, ^{

   NSURLSession *session = [NSURLSession sharedSession];
   NSURLSessionDataTask *dataTask = [session dataTaskWithURL:[NSURL URLWithString:@"https://www.websitethatdownloadsdata.com"] completionHandler:^(NSData *myData, NSURLResponse *response, NSError *error) {

       NSLog(@"Resp value from NSURL task: %@", response);
       NSLog(@"Error value from NSURL task: %@", error);

       if (error == nil) {

       NSLog(@"Downloading data...");

       }

       if (error != nil) {

       UIAlertController * alert = [UIAlertController alertControllerWithTitle:@"Network Problem" message:@"Cannot download data" preferredStyle:UIAlertControllerStyleAlert];
         UIAlertAction * actionOK = [UIAlertAction actionWithTitle:@"OK" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
                            //Here Add Your Action
             abort();
                        }];

                    [alert addAction:actionOK];

       [self presentViewController:alert animated:YES completion:nil];

       }
1

There are 1 answers

1
vadian On

The background queue is redundant because NSURLSession dispatches its tasks on a background thread anyway.

But you have to present the alert controller on the main thread

NSURLSession *session = [NSURLSession sharedSession];
NSURLSessionDataTask *dataTask = [session dataTaskWithURL:[NSURL URLWithString:@"https://www.websitethatdownloadsdata.com"] completionHandler:^(NSData *myData, NSURLResponse *response, NSError *error) {

   NSLog(@"Resp value from NSURL task: %@", response);
   NSLog(@"Error value from NSURL task: %@", error);

   if (error == nil) {

      NSLog(@"Downloading data...");

   } else {
      UIAlertController * alert = [UIAlertController alertControllerWithTitle:@"Network Problem" message:@"Cannot download data" preferredStyle:UIAlertControllerStyleAlert];
      UIAlertAction * actionOK = [UIAlertAction actionWithTitle:@"OK" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
         //Here Add Your Action
         abort();
      }];

      [alert addAction:actionOK];
      dispatch_async(dispatch_get_main_queue()) {
          [self presentViewController:alert animated:YES completion:nil];
      }
   }

}

And you should display also the reason of the error in the NSError instance