【问题标题】:iOS: NSURLConnection sendAsynchronousRequest delayed operation on NSImageViewiOS:NSImageView 上的 NSURLConnection sendAsynchronousRequest 延迟操作
【发布时间】:2013-02-27 08:26:06
【问题描述】:

我正在发送一个异步 http GET 请求,并且正在正确调用 completionHandler。像 NSLog 这样的回调中的代码会运行,因为我可以在日志中看到输出。但是,以下行: self.imageView.image = nil;似乎直到 NSLog 语句“到达这里”几秒钟后才生效。有谁知道发生了什么?示例代码如下:

在 ViewController.m 中:

@interface ViewController ()
@property (weak, nonatomic) IBOutlet UIImageView *imageView;
@end

@implementation ViewController
@synthesize imageView = _imageView;

-void viewDidLoad {
    // ImageView
    UIImage *image = [UIImage imageNamed:@"test.jpg"];
    self.imageView.backgroundColor = [UIColor blackColor];
    self.imageView.clipsToBounds = YES;
    self.imageView.image = image;
}

-void test {

    NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:@"http://someurl"] cachePolicy:NSURLRequestReloadIgnoringLocalAndRemoteCacheData timeoutInterval:10];
    [request setHTTPMethod:@"GET"];
    NSOperationQueue *queue = [[NSOperationQueue alloc] init];
    [NSURLConnection sendAsynchronousRequest:request queue:queue
completionHandler:^(NSURLResponse *response, NSData *data, NSError *error) {
        self.imageView.image = nil;
        NSLog(@"got here");
    }];
}

@结束

【问题讨论】:

  • 尝试将 nil 发送到队列参数以让 completionHandler 在主线程上执行
  • 我尝试设置 queue:nil,但这会导致 NSURLConnection 的 completionHandler 没有被调用。

标签: ios http asynchronous nsurlconnection


【解决方案1】:

啊,好像将队列参数设置为 [NSOperationQueue mainQueue] 固定在这里:

NSURLConnection sendAsynchronousRequest:queue:completionHandler: making multiple requests in a row?

【讨论】:

    【解决方案2】:

    正如 Undept 建议的那样,在主线程上调用这些行。像这样:

    dispatch_async (dispatch_get_main_queue (),  ^{
    self.imageView2.image = nil;
    self.imageView.image = nil;
    }); 
    

    【讨论】:

      猜你喜欢
      • 2014-05-08
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-09-26
      • 2015-02-25
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多