【发布时间】:2020-04-26 04:08:54
【问题描述】:
使用以下标准调用从服务器获取数据 - 如果出现错误,则使用标准警报 - 例如无法访问互联网。如果我关闭网络,应用程序崩溃,永远不会点击 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];
}
【问题讨论】:
-
"如果我关闭网络,应用程序会崩溃" 发生这种情况时,控制台中是否有崩溃日志?
-
另外,您从非主线程的线程中提供
UIAlertViewController,这会导致问题。 -
@rckoenes - 使用异步队列是获取数据然后更新 UI 的唯一方法 - 我为此奋斗了好几天......
-
所以它只是在 UI 的主线程中缺少调度?我认为这会在控制台中说明。这就是为什么我经常问问题的作者是否给出这个信息,指出要阅读它们。自己调试是一种重要的信息和平。
-
发布的代码有很多问题。您不应该在主线程之外执行任何 UI。
标签: objective-c xcode nsurl alertview