ios – SDWebImage不会加载远程图像,直到滚动

前端之家收集整理的这篇文章主要介绍了ios – SDWebImage不会加载远程图像,直到滚动前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我正在使用SDWeb Image库将远程映像加载到使用我创建的自定义单元格的表视图中.我只是用
  1. [cell.imageView setImageWithURL:url placeholderImage:[UIImage imageNamed:@"loading.jpg"]];

in cellForRowAtIndexPath:
现在的问题是它只加载可见单元格中的图像,而不是为了我不得不向上和向下滚动以使其加载的屏幕外的单元格.有没有办法我可以加载所有的图像,而不必滚动表视图.
提前致谢!!

解决方法

如果要预取行,则可以响应UIScrollViewDelegate方法来确定表滚动何时完成,从而触发行的预取.您可以使用SDWebImagePrefetcher执行预取(在我的原始答案我有点不屑一顾这个有用的类,但现在似乎工作相对较好):
  1. - (void)viewDidLoad
  2. {
  3. [super viewDidLoad];
  4.  
  5. // the details don't really matter here,but the idea is to fetch data,// call `reloadData`,and then prefetch the other images
  6.  
  7. NSURL *url = [NSURL URLWithString:kUrlWithJSONData];
  8. NSURLRequest *request = [NSURLRequest requestWithURL:url];
  9. [NSURLConnection sendAsynchronousRequest:request queue:[NSOperationQueue mainQueue] completionHandler:^(NSURLResponse *response,NSData *data,NSError *connectionError) {
  10. if (connectionError) {
  11. NSLog(@"sendAsynchronousRequest error: %@",connectionError);
  12. return;
  13. }
  14.  
  15. self.objects = [NSJSONSerialization JSONObjectWithData:data options:0 error:nil];
  16.  
  17. [self.tableView reloadData];
  18.  
  19. [self prefetchImagesForTableView:self.tableView];
  20. }];
  21. }
  22.  
  23. // some of the basic `UITableViewDataDelegate` methods have been omitted because they're not really relevant

这是一个简单的cellForRowAtIndexPath(不完全相关,但只是显示如果你使用SDWebImagePrefetcher,你不必乱七八糟的cellForRowAtIndexPath:

  1. - (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
  2. {
  3. static NSString *cellIdentifier = @"Cell";
  4. CustomCell *cell = [tableView dequeueReusableCellWithIdentifier:cellIdentifier];
  5. NSAssert([cell isKindOfClass:[CustomCell class]],@"cell should be CustomCell");
  6.  
  7. [cell.customImageView setImageWithURL:[self urlForIndexPath:indexPath] placeholderImage:nil];
  8. [cell.customLabel setText:[self textForIndexPath:indexPath]];
  9.  
  10. return cell;
  11. }

这些UIScrollViewDelegate方法在滚动完成时预取更多的行

  1. - (void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView
  2. {
  3. // if `decelerate` was true for `scrollViewDidEndDragging:willDecelerate:`
  4. // this will be called when the deceleration is done
  5.  
  6. [self prefetchImagesForTableView:self.tableView];
  7. }
  8.  
  9. - (void)scrollViewDidEndDragging:(UIScrollView *)scrollView willDecelerate:(BOOL)decelerate
  10. {
  11. // if `decelerate` is true,then we shouldn't start prefetching yet,because
  12. // `cellForRowAtIndexPath` will be hard at work returning cells for the currently visible
  13. // cells.
  14.  
  15. if (!decelerate)
  16. [self prefetchImagesForTableView:self.tableView];
  17. }

你显然需要实现一个预取例程.这可以获取可见单元格两边的单元格的NSIndexPath值,获取其图像URL,然后预取该数据.

  1. /** Prefetch a certain number of images for rows prior to and subsequent to the currently visible cells
  2. *
  3. * @param tableView The tableview for which we're going to prefetch images.
  4. */
  5.  
  6. - (void)prefetchImagesForTableView:(UITableView *)tableView
  7. {
  8. NSArray *indexPaths = [self.tableView indexPathsForVisibleRows];
  9. if ([indexPaths count] == 0) return;
  10.  
  11. NSIndexPath *minimumIndexPath = indexPaths[0];
  12. NSIndexPath *maximumIndexPath = [indexPaths lastObject];
  13.  
  14. // they should be sorted already,but if not,update min and max accordingly
  15.  
  16. for (NSIndexPath *indexPath in indexPaths)
  17. {
  18. if (indexPath.section < minimumIndexPath.section || (indexPath.section == minimumIndexPath.section && indexPath.row < minimumIndexPath.row)) minimumIndexPath = indexPath;
  19. if (indexPath.section > maximumIndexPath.section || (indexPath.section == maximumIndexPath.section && indexPath.row > maximumIndexPath.row)) maximumIndexPath = indexPath;
  20. }
  21.  
  22. // build array of imageURLs for cells to prefetch
  23.  
  24. NSMutableArray *imageURLs = [NSMutableArray array];
  25. indexPaths = [self tableView:tableView priorIndexPathCount:kPrefetchRowCount fromIndexPath:minimumIndexPath];
  26. for (NSIndexPath *indexPath in indexPaths)
  27. [imageURLs addObject:[self urlForIndexPath:indexPath]];
  28. indexPaths = [self tableView:tableView nextIndexPathCount:kPrefetchRowCount fromIndexPath:maximumIndexPath];
  29. for (NSIndexPath *indexPath in indexPaths)
  30. [imageURLs addObject:[self urlForIndexPath:indexPath]];
  31.  
  32. // now prefetch
  33.  
  34. if ([imageURLs count] > 0)
  35. {
  36. [[SDWebImagePrefetcher sharedImagePrefetcher] prefetchURLs:imageURLs];
  37. }
  38. }

这些是用于将NSIndexPath用于紧邻可见单元格之前的行以及紧挨在可见单元格之后的行的实用方法

  1. /** Retrieve NSIndexPath for a certain number of rows preceding particular NSIndexPath in the table view.
  2. *
  3. * @param tableView The tableview for which we're going to retrieve indexPaths.
  4. * @param count The number of rows to retrieve
  5. * @param indexPath The indexPath where we're going to start (presumably the first visible indexPath)
  6. *
  7. * @return An array of indexPaths.
  8. */
  9.  
  10. - (NSArray *)tableView:(UITableView *)tableView priorIndexPathCount:(NSInteger)count fromIndexPath:(NSIndexPath *)indexPath
  11. {
  12. NSMutableArray *indexPaths = [NSMutableArray array];
  13. NSInteger row = indexPath.row;
  14. NSInteger section = indexPath.section;
  15.  
  16. for (NSInteger i = 0; i < count; i++) {
  17. if (row == 0) {
  18. if (section == 0) {
  19. return indexPaths;
  20. } else {
  21. section--;
  22. row = [tableView numberOfRowsInSection:section] - 1;
  23. }
  24. } else {
  25. row--;
  26. }
  27. [indexPaths addObject:[NSIndexPath indexPathForRow:row inSection:section]];
  28. }
  29.  
  30. return indexPaths;
  31. }
  32.  
  33. /** Retrieve NSIndexPath for a certain number of following particular NSIndexPath in the table view.
  34. *
  35. * @param tableView The tableview for which we're going to retrieve indexPaths.
  36. * @param count The number of rows to retrieve
  37. * @param indexPath The indexPath where we're going to start (presumably the last visible indexPath)
  38. *
  39. * @return An array of indexPaths.
  40. */
  41.  
  42. - (NSArray *)tableView:(UITableView *)tableView nextIndexPathCount:(NSInteger)count fromIndexPath:(NSIndexPath *)indexPath
  43. {
  44. NSMutableArray *indexPaths = [NSMutableArray array];
  45. NSInteger row = indexPath.row;
  46. NSInteger section = indexPath.section;
  47. NSInteger rowCountForSection = [tableView numberOfRowsInSection:section];
  48.  
  49. for (NSInteger i = 0; i < count; i++) {
  50. row++;
  51. if (row == rowCountForSection) {
  52. row = 0;
  53. section++;
  54. if (section == [tableView numberOfSections]) {
  55. return indexPaths;
  56. }
  57. rowCountForSection = [tableView numberOfRowsInSection:section];
  58. }
  59. [indexPaths addObject:[NSIndexPath indexPathForRow:row inSection:section]];
  60. }
  61.  
  62. return indexPaths;
  63. }

这里有很多,但实际上,SDWebImage及其SDWebImagePrefetcher正在大力提升.

为了完整起见,我将原来的答案包括在内.

原来的答案:

如果要使用SDWebImage进行某些预取,则可以执行以下操作:

>添加一个完成块到你的setImageWithURL调用

  1. - (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
  2. {
  3. NSLog(@"%s",__FUNCTION__);
  4.  
  5. static NSString *cellIdentifier = @"Cell";
  6. UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:cellIdentifier];
  7.  
  8. TableModelRow *rowData = self.objects[indexPath.row];
  9.  
  10. cell.textLabel.text = rowData.title;
  11. [cell.imageView setImageWithURL:rowData.url
  12. placeholderImage:[UIImage imageNamed:@"placeholder.png"]
  13. completed:^(UIImage *image,NSError *error,SDImageCacheType cacheType) {
  14. [self prefetchImagesForTableView:tableView];
  15. }];
  16.  
  17. return cell;
  18. }

我必须承认,我不喜欢在这里调用我的预取程序(我希望iOS有一些很好的didFinishTableRefresh委托方法),但它的工作原理,即使它比我想要的更多的时间调用例程.我只需确保下面的例程确保它不会产生冗余请求.
>无论如何,我写一个预取例程,寻找,接下来的十个图像:

  1. const NSInteger kPrefetchRowCount = 10;
  2.  
  3. - (void)prefetchImagesForTableView:(UITableView *)tableView
  4. {
  5. // determine the minimum and maximum visible rows
  6.  
  7. NSArray *indexPathsForVisibleRows = [tableView indexPathsForVisibleRows];
  8. NSInteger minimumVisibleRow = [indexPathsForVisibleRows[0] row];
  9. NSInteger maximumVisibleRow = [indexPathsForVisibleRows[0] row];
  10.  
  11. for (NSIndexPath *indexPath in indexPathsForVisibleRows)
  12. {
  13. if (indexPath.row < minimumVisibleRow) minimumVisibleRow = indexPath.row;
  14. if (indexPath.row > maximumVisibleRow) maximumVisibleRow = indexPath.row;
  15. }
  16.  
  17. // now iterate through our model;
  18. // `self.objects` is an array of `TableModelRow` objects,one object
  19. // for every row of the table.
  20.  
  21. [self.objects enumerateObjectsUsingBlock:^(TableModelRow *obj,NSUInteger idx,BOOL *stop) {
  22. NSAssert([obj isKindOfClass:[TableModelRow class]],@"Expected TableModelRow object");
  23.  
  24. // if the index is within `kPrefetchRowCount` rows of our visible rows,let's
  25. // fetch the image,if it hasn't already done so.
  26.  
  27. if ((idx < minimumVisibleRow && idx >= (minimumVisibleRow - kPrefetchRowCount)) ||
  28. (idx > maximumVisibleRow && idx <= (maximumVisibleRow + kPrefetchRowCount)))
  29. {
  30. // my model object has method for initiating a download if needed
  31.  
  32. [obj downloadImageIfNeeded];
  33. }
  34. }];
  35. }

>在下载例程中,您可以检查图像下载是否已经启动,如果不是,则启动它.要使用SDWebImage执行此操作,我在TableModelRow类(支持表的各行的模型类)中保留一个弱指针到web图像操作:

  1. @property (nonatomic,weak) id<SDWebImageOperation> webImageOperation;

如果还没有,请下载downloadImageIfNeeded例程(您可以看到为什么这个弱点非常重要)我正在检查这个行是否已经有一个操作挂起,然后再启动另一个).我没有对下载的图像做任何事情(简而言之,为了调试目的,记录下载完成的事实),而只是下载并让SDImageWeb跟踪我的缓存图像,所以当cellForRowAtIndexPath稍后请求图像随着用户向下滚动,它在那里,准备好等待.

  1. - (void)downloadImageIfNeeded
  2. {
  3. if (self.webImageOperation)
  4. return;
  5.  
  6. SDWebImageManager *imageManager = [SDWebImageManager sharedManager];
  7.  
  8. self.webImageOperation = [imageManager downloadWithURL:self.url
  9. options:0
  10. progress:nil
  11. completed:^(UIImage *image,SDImageCacheType cacheType,BOOL finished) {
  12. NSLog(@"%s: downloaded %@",__FUNCTION__,self.title);
  13. // I'm not going to do anything with the image,but `SDWebImage` has now cached it for me
  14. }];
  15. }

我认为,首先调用imageManager.imageCache实例方法queryDiskCacheForKey可能会更加强大,但是在进行了一些测试之后,它看起来不像那样(而且对于我们来说,downloadWithURL对我们来说是这样).

我应该指出,SDImageWeb库确实有一个SDWebImagePrefetcher类(见the documentation).类的名称是非常有希望的,但是看代码,所有的尊重,否则优秀的图书馆,这对我来说并不觉得非常强大(例如,这是一个简单的URL提取列表,如果你再次这样做,它取消了先前的列表,没有“添加到队列”或任何类似的概念.这是一个有希望的概念,但执行有点薄弱.当我尝试它,我的UX受到明显的影响.

所以,我倾向于不使用SDWebImagePrefetcher(至少要改进),并且坚持我的基本预取技术.这不是非常复杂的,但它似乎工作.

猜你在找的iOS相关文章