iOS 在后台下载图像并更新 UI

标签 ios nsurlconnection nstimer nsrunloop

我正在尝试通过从服务器下载图像,每 1 秒用新图像更新一次 ImageView 。下载发生在后台线程中。下面显示的是代码

 NSTimer *timer = [NSTimer timerWithTimeInterval:0.5
                                         target:self
                                       selector:@selector(timerFired:)
                                       userInfo:nil repeats:YES];
[[NSRunLoop mainRunLoop] addTimer:timer forMode:NSRunLoopCommonModes];



-(void)timerFired:(id)sender
 {
    NSURLRequest *request=[[NSURLRequest alloc]initWithURL:[NSURL      


    URLWithString:@"http://192.168.4.116:8080/RMC/ImageWithCommentData.jpg"]];

    NSOperationQueue *queueTmp = [[NSOperationQueue alloc] init];

   [NSURLConnection sendAsynchronousRequest:request queue:queueTmp completionHandler:^(NSURLResponse *response, NSData *data, NSError *error)
   {
     if ([data length] > 0 && error == nil)
     {

         [self performSelectorOnMainThread:@selector(processImageData:) withObject:data waitUntilDone:TRUE modes:nil];

     }

     else if ([data length] == 0 && error == nil)
     {

     }
     else if (error != nil)
     {



     }

 }];
}


-(void)processImageData:(NSData*)imageData
{
  NSLog(@"data downloaded");
  [self.hmiImageView setImage:[UIImage imageWithData:imageData]];
 }

我的图片正在下载。但未调用 ProcessImageData 方法。请帮我解决这个问题。

最佳答案

问题是您正在异步调用 NSURLConnection :

 [NSURLConnection sendAsynchronousRequest:request queue:queueTmp completionHandler:^(NSURLResponse *response, NSData *data, NSError *error)

因此,在您获取任何数据之前:if ([data length] > 0 && error == nil) get called 。 所以数据长度保持为 0,这就是为什么不调用您的方法的原因。为了达到您的要求,您可以这样做:

dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_HIGH, 0ul);
    dispatch_async(queue, ^(void) {

            NSData *imageData = //download image here 
            UIImage* image = [[UIImage alloc] initWithData:imageData];
            if (image) {
                 dispatch_async(dispatch_get_main_queue(), ^{
                        //set image here
                     }
                 });
             }
        });

关于iOS 在后台下载图像并更新 UI,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19533248/

相关文章:

ios - 继承 UIButton 外观的 UITableViewCell 披露指示器

ios - NSURLConnection 和 sendAsynchronousRequest :queue:completionHandler: - does the completion block run in the main thread

ios - 在执行下一条语句之前如何等待 NSURLConnection 委托(delegate)完成?

iphone - NSTimer 因访问错误而崩溃

ios - 适用于 iOS 的 Ionic 和 Cordova 中的奇怪内存泄漏

ios - 在 iOS 中添加 FFMPEG 库

objective-c - 从 NSURLResponse 完成 block 中获取数据

ios - 双击识别器不适用于 NSTimer 运行

cocoa - 如何保证NSTimer始终在NSView中运行?

ios - Swift:无法使用 Firebase 将数据同步到 TableView