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

我正在使用SDWeb Image库将远程映像加载到使用我创建的自定义单元格的表视图中.我只是用
[cell.imageView setImageWithURL:url placeholderImage:[UIImage imageNamed:@"loading.jpg"]];

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

解决方法

如果要预取行,则可以响应UIScrollViewDelegate方法来确定表滚动何时完成,从而触发行的预取.您可以使用SDWebImagePrefetcher执行预取(在我的原始答案我有点不屑一顾这个有用的类,但现在似乎工作相对较好):
- (void)viewDidLoad
{
    [super viewDidLoad];

    // the details don't really matter here,but the idea is to fetch data,// call `reloadData`,and then prefetch the other images

    NSURL *url = [NSURL URLWithString:kUrlWithJSONData];
    NSURLRequest *request = [NSURLRequest requestWithURL:url];
    [NSURLConnection sendAsynchronousRequest:request queue:[NSOperationQueue mainQueue] completionHandler:^(NSURLResponse *response,NSData *data,NSError *connectionError) {
        if (connectionError) {
            NSLog(@"sendAsynchronousRequest error: %@",connectionError);
            return;
        }

        self.objects = [NSJSONSerialization JSONObjectWithData:data options:0 error:nil];

        [self.tableView reloadData];

        [self prefetchImagesForTableView:self.tableView];
    }];
}

// some of the basic `UITableViewDataDelegate` methods have been omitted because they're not really relevant

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

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString *cellIdentifier = @"Cell";
    CustomCell *cell = [tableView dequeueReusableCellWithIdentifier:cellIdentifier];
    NSAssert([cell isKindOfClass:[CustomCell class]],@"cell should be CustomCell");

    [cell.customImageView setImageWithURL:[self urlForIndexPath:indexPath] placeholderImage:nil];
    [cell.customLabel setText:[self textForIndexPath:indexPath]];

    return cell;
}

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

- (void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView
{
    // if `decelerate` was true for `scrollViewDidEndDragging:willDecelerate:`
    // this will be called when the deceleration is done

    [self prefetchImagesForTableView:self.tableView];
}

- (void)scrollViewDidEndDragging:(UIScrollView *)scrollView willDecelerate:(BOOL)decelerate
{
    // if `decelerate` is true,then we shouldn't start prefetching yet,because
    // `cellForRowAtIndexPath` will be hard at work returning cells for the currently visible
    // cells.

    if (!decelerate)
        [self prefetchImagesForTableView:self.tableView];
}

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

/** Prefetch a certain number of images for rows prior to and subsequent to the currently visible cells
 *
 * @param  tableView   The tableview for which we're going to prefetch images.
 */

- (void)prefetchImagesForTableView:(UITableView *)tableView
{
    NSArray *indexPaths = [self.tableView indexPathsForVisibleRows];
    if ([indexPaths count] == 0) return;

    NSIndexPath *minimumIndexPath = indexPaths[0];
    NSIndexPath *maximumIndexPath = [indexPaths lastObject];

    // they should be sorted already,but if not,update min and max accordingly

    for (NSIndexPath *indexPath in indexPaths)
    {
        if (indexPath.section < minimumIndexPath.section || (indexPath.section == minimumIndexPath.section && indexPath.row < minimumIndexPath.row)) minimumIndexPath = indexPath;
        if (indexPath.section > maximumIndexPath.section || (indexPath.section == maximumIndexPath.section && indexPath.row > maximumIndexPath.row)) maximumIndexPath = indexPath;
    }

    // build array of imageURLs for cells to prefetch

    NSMutableArray *imageURLs = [NSMutableArray array];
    indexPaths = [self tableView:tableView priorIndexPathCount:kPrefetchRowCount fromIndexPath:minimumIndexPath];
    for (NSIndexPath *indexPath in indexPaths)
        [imageURLs addObject:[self urlForIndexPath:indexPath]];
    indexPaths = [self tableView:tableView nextIndexPathCount:kPrefetchRowCount fromIndexPath:maximumIndexPath];
    for (NSIndexPath *indexPath in indexPaths)
        [imageURLs addObject:[self urlForIndexPath:indexPath]];

    // now prefetch

    if ([imageURLs count] > 0)
    {
        [[SDWebImagePrefetcher sharedImagePrefetcher] prefetchURLs:imageURLs];
    }
}

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

/** Retrieve NSIndexPath for a certain number of rows preceding particular NSIndexPath in the table view.
 *
 * @param  tableView  The tableview for which we're going to retrieve indexPaths.
 * @param  count      The number of rows to retrieve
 * @param  indexPath  The indexPath where we're going to start (presumably the first visible indexPath)
 *
 * @return            An array of indexPaths.
 */

- (NSArray *)tableView:(UITableView *)tableView priorIndexPathCount:(NSInteger)count fromIndexPath:(NSIndexPath *)indexPath
{
    NSMutableArray *indexPaths = [NSMutableArray array];
    NSInteger row = indexPath.row;
    NSInteger section = indexPath.section;

    for (NSInteger i = 0; i < count; i++) {
        if (row == 0) {
            if (section == 0) {
                return indexPaths;
            } else {
                section--;
                row = [tableView numberOfRowsInSection:section] - 1;
            }
        } else {
            row--;
        }
        [indexPaths addObject:[NSIndexPath indexPathForRow:row inSection:section]];
    }

    return indexPaths;
}

/** Retrieve NSIndexPath for a certain number of following particular NSIndexPath in the table view.
 *
 * @param  tableView  The tableview for which we're going to retrieve indexPaths.
 * @param  count      The number of rows to retrieve
 * @param  indexPath  The indexPath where we're going to start (presumably the last visible indexPath)
 *
 * @return            An array of indexPaths.
 */

- (NSArray *)tableView:(UITableView *)tableView nextIndexPathCount:(NSInteger)count fromIndexPath:(NSIndexPath *)indexPath
{
    NSMutableArray *indexPaths = [NSMutableArray array];
    NSInteger row = indexPath.row;
    NSInteger section = indexPath.section;
    NSInteger rowCountForSection = [tableView numberOfRowsInSection:section];

    for (NSInteger i = 0; i < count; i++) {
        row++;
        if (row == rowCountForSection) {
            row = 0;
            section++;
            if (section == [tableView numberOfSections]) {
                return indexPaths;
            }
            rowCountForSection = [tableView numberOfRowsInSection:section];
        }
        [indexPaths addObject:[NSIndexPath indexPathForRow:row inSection:section]];
    }

    return indexPaths;
}

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

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

原来的答案:

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

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

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    NSLog(@"%s",__FUNCTION__);

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

    TableModelRow *rowData = self.objects[indexPath.row];

    cell.textLabel.text = rowData.title;
    [cell.imageView setImageWithURL:rowData.url
                   placeholderImage:[UIImage imageNamed:@"placeholder.png"]
                          completed:^(UIImage *image,NSError *error,SDImageCacheType cacheType) {
                              [self prefetchImagesForTableView:tableView];
                          }];

    return cell;
}

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

const NSInteger kPrefetchRowCount = 10;

- (void)prefetchImagesForTableView:(UITableView *)tableView
{
    // determine the minimum and maximum visible rows

    NSArray *indexPathsForVisibleRows = [tableView indexPathsForVisibleRows];
    NSInteger minimumVisibleRow = [indexPathsForVisibleRows[0] row];
    NSInteger maximumVisibleRow = [indexPathsForVisibleRows[0] row];

    for (NSIndexPath *indexPath in indexPathsForVisibleRows)
    {
        if (indexPath.row < minimumVisibleRow) minimumVisibleRow = indexPath.row;
        if (indexPath.row > maximumVisibleRow) maximumVisibleRow = indexPath.row;
    }

    // now iterate through our model;
    // `self.objects` is an array of `TableModelRow` objects,one object
    // for every row of the table.

    [self.objects enumerateObjectsUsingBlock:^(TableModelRow *obj,NSUInteger idx,BOOL *stop) {
        NSAssert([obj isKindOfClass:[TableModelRow class]],@"Expected TableModelRow object");

        // if the index is within `kPrefetchRowCount` rows of our visible rows,let's
        // fetch the image,if it hasn't already done so.

        if ((idx < minimumVisibleRow && idx >= (minimumVisibleRow - kPrefetchRowCount)) ||
            (idx > maximumVisibleRow && idx <= (maximumVisibleRow + kPrefetchRowCount)))
        {
            // my model object has method for initiating a download if needed

            [obj downloadImageIfNeeded];
        }
    }];
}

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

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

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

- (void)downloadImageIfNeeded
{
    if (self.webImageOperation)
        return;

    SDWebImageManager *imageManager = [SDWebImageManager sharedManager];

    self.webImageOperation = [imageManager downloadWithURL:self.url
                                                   options:0
                                                  progress:nil
                                                 completed:^(UIImage *image,SDImageCacheType cacheType,BOOL finished) {
                                                     NSLog(@"%s: downloaded %@",__FUNCTION__,self.title);
                                                     // I'm not going to do anything with the image,but `SDWebImage` has now cached it for me
                                                 }];
}

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

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

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

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐


当我们远离最新的 iOS 16 更新版本时,我们听到了困扰 Apple 最新软件的错误和性能问题。
欧版/美版 特别说一下,美版选错了 可能会永久丧失4G,不过只有5%的概率会遇到选择运营商界面且部分必须连接到iTunes才可以激活
一般在接外包的时候, 通常第三方需要安装你的app进行测试(这时候你的app肯定是还没传到app store之前)。
前言为了让更多的人永远记住12月13日,各大厂都在这一天将应用变灰了。那么接下来我们看一下Flutter是如何实现的。Flutter中实现整个App变为灰色在Flutter中实现整个App变为灰色是非常简单的,只需要在最外层的控件上包裹ColorFiltered,用法如下:ColorFiltered(颜色过滤器)看名字就知道是增加颜色滤镜效果的,ColorFiltered( colorFilter:ColorFilter.mode(Colors.grey, BlendMode.
flutter升级/版本切换
(1)在C++11标准时,open函数的文件路径可以传char指针也可以传string指针,而在C++98标准,open函数的文件路径只能传char指针;(2)open函数的第二个参数是打开文件的模式,从函数定义可以看出,如果调用open函数时省略mode模式参数,则默认按照可读可写(ios_base:in | ios_base::out)的方式打开;(3)打开文件时的mode的模式是从内存的角度来定义的,比如:in表示可读,就是从文件读数据往内存读写;out表示可写,就是把内存数据写到文件中;
文章目录方法一:分别将图片和文字置灰UIImage转成灰度图UIColor转成灰度颜色方法二:给App整体添加灰色滤镜参考App页面置灰,本质是将彩色图像转换为灰度图像,本文提供两种方法实现,一种是App整体置灰,一种是单个页面置灰,可结合具体的业务场景使用。方法一:分别将图片和文字置灰一般情况下,App页面的颜色深度是24bit,也就是RGB各8bit;如果算上Alpha通道的话就是32bit,RGBA(或者ARGB)各8bit。灰度图像的颜色深度是8bit,这8bit表示的颜色不是彩色,而是256
领导让调研下黑(灰)白化实现方案,自己调研了两天,根据网上资料,做下记录只是学习过程中的记录,还是写作者牛逼
让学前端不再害怕英语单词(二),通过本文,可以对css,js和es6的单词进行了在逻辑上和联想上的记忆,让初学者更快的上手前端代码
用Python送你一颗跳动的爱心
在uni-app项目中实现人脸识别,既使用uni-app中的live-pusher开启摄像头,创建直播推流。通过快照截取和压缩图片,以base64格式发往后端。
商户APP调用微信提供的SDK调用微信支付模块,商户APP会跳转到微信中完成支付,支付完后跳回到商户APP内,最后展示支付结果。CSDN前端领域优质创作者,资深前端开发工程师,专注前端开发,在CSDN总结工作中遇到的问题或者问题解决方法以及对新技术的分享,欢迎咨询交流,共同学习。),验证通过打开选择支付方式弹窗页面,选择微信支付或者支付宝支付;4.可取消支付,放弃支付会返回会员页面,页面提示支付取消;2.判断支付方式,如果是1,则是微信支付方式。1.判断是否在微信内支付,需要在微信外支付。
Mac命令行修改ipa并重新签名打包
首先在 iOS 设备中打开开发者模式。位于:设置 - 隐私&安全 - 开发者模式(需重启)
一 现象导入MBProgressHUD显示信息时,出现如下异常现象Undefined symbols for architecture x86_64: "_OBJC_CLASS_$_MBProgressHUD", referenced from: objc-class-ref in ViewController.old: symbol(s) not found for architecture x86_64clang: error: linker command failed wit
Profiles >> 加号添加 >> Distribution >> "App Store" >> 选择 2.1 创建的App ID >> 选择绑定 2.3 的发布证书(.cer)>> 输入描述文件名称 >> Generate 生成描述文件 >> Download。Certificates >> 加号添加 >> "App Store and Ad Hoc" >> “Choose File...” >> 选择上一步生成的证书请求文件 >> Continue >> Download。
今天有需求,要实现的功能大致如下:在安卓和ios端实现分享功能可以分享链接,图片,文字,视频,文件,等欢迎大佬多多来给萌新指正,欢迎大家来共同探讨。如果各位看官觉得文章有点点帮助,跪求各位给点个“一键三连”,谢啦~声明:本博文章若非特殊注明皆为原创原文链接。