Search code examples
uitableviewcocoa-touchuikitlazy-loadingimage-loading

Loading image from byte array stream in UITableViewCell


I am implementing a UITableView with custom UITableViewCell. There is UIImageView there for displaying some image. But the api I am given , does not contain the download links of the images that I'll have to show in each UITableViewCell. For getting the images , I'll need to call another GET request that returns byte array stream of the image to be shown on the corresponding Cell.

I know , I can make an Image from NSData coming from the api. But I am not sure how much efficient idea that would be , I am worrying about memory and performance issue. And I want to do asynchronous loading in UITableViewCell and image cacheing also so that It take less time in later calls. So , what can be a efficient approach here ? And also some suggestion about any good library that can help me doing this would be great.


Solution

  • This is how I have solved it. I haven't used caching yet , but this is enough to show them properly in UITableViewCell. Here's the method I have used.

    + (void)downloadImageWithURL:(NSMutableURLRequest *)request completionBlock:(void (^)(BOOL succeeded, UIImage *image))completionBlock
    {
        [NSURLConnection sendAsynchronousRequest:request
                                           queue:[NSOperationQueue mainQueue]
                               completionHandler:^(NSURLResponse *response, NSData *data, NSError *error) {
    
                                   NSHTTPURLResponse* httpResponse = (NSHTTPURLResponse*)response;
                                   int statusCode = httpResponse.statusCode ;
                                   NSLog(@"Status Code Imageloading : %d" , statusCode);
    
                                   if(statusCode == 200){
                                       UIImage *image = [[UIImage alloc] initWithData:data];
                                       NSLog(@"Success");
                                       completionBlock(YES,image);
                                   } else {
                                       NSLog(@"Failure");
                                       completionBlock(NO,nil);
                                   }
        }];
    }