Karthick
Karthick

Reputation: 382

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.

Upvotes: 0

Views: 1567

Answers (1)

V-Xtreme
V-Xtreme

Reputation: 7333

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

Upvotes: 1

Related Questions