Rob85
Rob85

Reputation: 1729

Reduce scrolling lag when using server side images for Tableview

I currently have a tableView which can display any number of results. each row has an image which is pulled from a server. Assuming the Server is fast and the device has a reliable connection how can i reduce the lag when scrolling through the list.

I looked at loading the images on the background thread and this has definitely improved things however you can clearly see the images rendering as you scroll up and down.

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
  {

      static NSString *CellIdentifier = @"Cell";
      UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];

      if (cell == nil)
      {
          cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier];
      }

      if (tableView == self.searchDisplayController.searchResultsTableView)
      {
         cell.textLabel.text = [self.searchResult objectAtIndex:indexPath.row];
      }
      else
      {
         cell.textLabel.text = self.TableData[indexPath.row];
      }
      _ImageURL = self.ImageData[indexPath.row];
      dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_HIGH, 0ul);
      dispatch_async(queue, ^
      {
          UIImage *image = [UIImage imageWithData:[NSData dataWithContentsOfURL:[NSURL URLWithString:_ImageURL]]];
          dispatch_sync(dispatch_get_main_queue(), ^
          {

              [[cell imageView] setImage:image];
              [cell setNeedsLayout];
          });
      });
      return cell;
 }

Is there any method to improving this or is it more likely to be a constraint of the server speed and device bandwidth. My server is no Facebook server but its a decent paid one that i use for other applications.

Also since moving the images to the background task i notice that now and again a row will miss loading an image, any thoughts on this?

Upvotes: 0

Views: 217

Answers (1)

Rached Anis
Rached Anis

Reputation: 349

I recommend you to use SDWebImage library, everything will be handled for you, from async downloads to caching management. Here is the link for downloading and documentation.

You can also use Facebook's AsyncDisplayKit if you don't need image caching.

Good Luck.

Upvotes: 3

Related Questions