0

使用以下标准调用从服务器获取数据 - 如果出现错误,则使用标准警报 - 例如无法访问互联网。如果我关闭网络,应用程序就会崩溃,永远不会NSLog调用 *response 或 *error,永远不会进入警报。

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

       }
4

1 回答 1

2

后台队列是多余的,因为NSURLSession无论如何都会在后台线程上调度其任务。

但是您必须在主线程上显示警报控制器

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

}

您还应该在NSError实例中显示错误的原因

于 2020-01-08T15:49:24.970 回答