简体   繁体   中英

iOS Downloading image in background and updating the UI

I am trying update an imageview with new image for every 1 sec by downloading the image from the server. The downloading happens in background thread. Below shown is the code

 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]];
 }

My image is getting downloaded. But ProcessImageData method is not called. Please help me to fix this issue.

The problem is you are calling NSURLConnection asynchronously :

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

so before you get any data the : if ([data length] > 0 && error == nil) get called . so the data length remains 0 thats why your method is not called . for achieving your requirement you can do like :

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
                     }
                 });
             }
        });

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM