【问题标题】:UIAlertView takes too long when using inside NSURLSession在 NSURLSession 中使用时 UIAlertView 耗时太长
【发布时间】:2015-04-01 03:47:56
【问题描述】:

我正在使用NSURLSession 从我的服务器获取一些信息。 获得数据后,我将其显示在UIAlertView 中,但显示时间太长。我用NSLog 打印数据,它几乎立即打印出来……那么发生了什么?方法dataTaskWithRequest 不是异步的吗?为什么弹出警报视图需要这么长时间?

NSURLSession *session;
session = [NSURLSession sharedSession];
NSURL * url = [NSURL URLWithString:[DRESSABLE_IP stringByAppendingString:@"index.php"]];
NSMutableURLRequest * urlRequest = [[NSMutableURLRequest alloc] initWithURL:url cachePolicy:CONNECTION_CACHEPOLICY  timeoutInterval:CONNECTION_TIMEOUT];
[urlRequest setHTTPMethod:@"POST"];
NSURLSessionDataTask *dataTask = [session dataTaskWithRequest:urlRequest 
completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) {
        NSString *total = [[NSString alloc]initWithData:data encoding:NSUTF8StringEncoding];
        [[[UIAlertView alloc] initWithTitle:@"Title" message:total delegate:self cancelButtonTitle:@"Ok" otherButtonTitles:nil] show];
 }];

【问题讨论】:

    标签: ios ios8 uialertview nsurlsession nsurlsessiondatatask


    【解决方案1】:

    所有 UI 活动都必须在主队列中完成。

    NSURLSession *session;
    session = [NSURLSession sharedSession];
    NSURL * url = [NSURL URLWithString:[DRESSABLE_IP stringByAppendingString:@"index.php"]];
    NSMutableURLRequest * urlRequest = [[NSMutableURLRequest alloc] initWithURL:url cachePolicy:CONNECTION_CACHEPOLICY  timeoutInterval:CONNECTION_TIMEOUT];
    [urlRequest setHTTPMethod:@"POST"];
    NSURLSessionDataTask *dataTask = [session dataTaskWithRequest:urlRequest 
    completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) {
            NSString *total = [[NSString alloc]initWithData:data encoding:NSUTF8StringEncoding];
    dispatch_async(dispatch_get_main_queue(),^{
            [[[UIAlertView alloc] initWithTitle:@"Title" message:total delegate:self cancelButtonTitle:@"Ok" otherButtonTitles:nil] show];
    });
     }];
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-08-07
      • 2018-02-27
      • 2013-05-28
      • 2014-05-30
      相关资源
      最近更新 更多