使用以下标准调用从服务器获取数据 - 如果出现错误,则使用标准警报 - 例如无法访问互联网。如果我关闭网络,应用程序就会崩溃,永远不会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];
}