How can i download photos by order of cells in UITableView with dispatch_async?

不羁的心 提交于 2019-12-22 01:26:15

问题


I have a UITableView that has photos, i get these photos from URLs and i use the block for downloading these photo asynchronously, and i want these photos be downloaded by order of the cells in the UITableView?

   // Download the images from the review of the businesses and put them into the "imageArray"
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_HIGH, 0), ^{
    NSData *imageData = [NSData dataWithContentsOfURL:[NSURL URLWithString:[NSString stringWithFormat:@"http://feature.site.com%@",entry.avatarUrl]]];
    UIImage *imageField = [[UIImage alloc] initWithData:imageData];
    dispatch_async(dispatch_get_main_queue(), ^{
        [imageArray addObject:imageField];
        photo.image = imageField;
    });
});

回答1:


You need to do something like this:

1) First create and mutable array full of NSNull.

2) On CellForRowAtIndexPath, ask if the array at that indexPath.row is equal to NSNull.

2.1) If is equal, download the image like this:

dispatch_queue_t bgqueue = dispatch_queue_create("com.yourApp.yyourclass.bgqueue", NULL);
dispatch_async(bgqueue, ^{
    NSData *imageData = [NSData dataWithContentsOfURL:[NSURL URLWithString:[NSString stringWithFormat:@"http://feature.site.com%@",entry.avatarUrl]]];
    UIImage *imageField = [[UIImage alloc] initWithData:imageData];
    dispatch_async(dispatch_get_main_queue(), ^{
        [imageArray addObject:imageField atIndex:indexPath.row];
        tableView reloadRowsAtIndexPaths:[NSArray arrayWithObject:indexPath] withRowAnimation:UITableViewRowAnimationNone]
    });
});
dispatch_release(bgqueue);

2.2) If is not equal(have an Image) just set the image in the array.

photo.image = [imageArray objectAtIndex:indexPath.row];

By Doing this your images keep cell order and you increase the performance of the scrolling.

PD-1: You should use a library that handles the download and caching of the images like HTTPRequest

PD-2: In your Did reReceiveMemoryWarning you should do something like this:

- (void)didReceiveMemoryWarning
{
    // Releases the view if it doesn't have a superview.
    [super didReceiveMemoryWarning];

    [imagesArray removeAllObjects];
    //Fill the array with NSNull's again;

}

Further Improvement:

In the Array you could have 3 states:

  1. NSNull: No Image
  2. NewState(EG. some string): Image being downloaded.
  3. UIImage: Image Downloaded.

With this you could prevent for downloading several times the same image if you scroll up and down continuously while the images are being downloaded.



来源:https://stackoverflow.com/questions/8636499/how-can-i-download-photos-by-order-of-cells-in-uitableview-with-dispatch-async

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!