1

I'm trying to load images from server to cell asynchronously. But images not changing while scrolling, only after scrolling stops. "loaded" messages appear in console only after scrolling stops too. I want images appear in cell while scrolling.

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    CustomCell *cell = (CustomCell *)[_tableView dequeueReusableCellWithIdentifier:@"CustomCell"];
    ZTVRequest *request = [[ZTVRequest alloc] init];
    [request getSmallImg completionHandler:^(UIImage *img, NSError *error) {
        if (! error) {
            NSLog(@"loaded")
            cell.coverImgView.image = img;
        }
    }];

    return cell;
}
user1561346
  • 502
  • 3
  • 13
  • 28
  • 1
    Your `cell.coverImgView.image = omg;` appears to be running on a background thread and so will not be updated immediately. You must dispatch the image load to the main queue using something like: `dispatch_async(dispatch_get_main_queue(), ^{ cell.coverImgView.image = img; })` . See: http://stackoverflow.com/q/4944363/558933 – Robotic Cat Jan 06 '15 at 20:53
  • Not helped. I've added answer. – user1561346 Jan 06 '15 at 21:16

1 Answers1

1

I'm using NSURLConnection for loading image. I found solution in this answer: https://stackoverflow.com/a/1995318/1561346 by Daniel Dickison

Here it is:

The reason the connection delegate messages aren't firing until you stop scrolling is because during scrolling, the run loop is in UITrackingRunLoopMode. By default, NSURLConnection schedules itself in NSDefaultRunLoopMode only, so you don't get any messages while scrolling.

Here's how to schedule the connection in the "common" modes, which includes UITrackingRunLoopMode:

NSURLRequest *request = ...
NSURLConnection *connection = [[NSURLConnection alloc]
                               initWithRequest:request
                               delegate:self
                               startImmediately:NO];
[connection scheduleInRunLoop:[NSRunLoop currentRunLoop]
            forMode:NSRunLoopCommonModes];
[connection start];

Note that you have to specify startImmediately:NO in the initializer, which seems to run counter to Apple's documentation that suggests you can change run loop modes even after it has started.

Community
  • 1
  • 1
user1561346
  • 502
  • 3
  • 13
  • 28