开发者社区> 游贤明> 正文

使用开源库 SDWebImage 异步下载缓存图片(持续更新)

简介:
+关注继续查看

source  https://github.com/rs/SDWebImage

APIdoc  http://hackemist.com/SDWebImage/doc

Asynchronous image downloader with cache support with an UIImageView category

UIImageView的类目,支持异步图片下载,支持缓存机制

This library provides a category for UIImageVIew with support for remote images coming from the web.

这个库给UIImageView提供类目,支持远程下载图片(从网络上)

It provides:

  • An UIImageView category adding web image and cache management to the Cocoa Touch framework
  • An asynchronous image downloader
  • An asynchronous memory + disk image caching with automatic cache expiration handling
  • Animated GIF support
  • WebP format support
  • A background image decompression
  • A guarantee that the same URL won't be downloaded several times
  • A guarantee that bogus URLs won't be retried again and again
  • A guarantee that main thread will never be blocked
  • Performances!
  • Use GCD and ARC
  • Arm64 support
  • 一个UIImageView的类目,给 Cocoa Touch 框架添加了异步下载远程图片以及管理图片缓存的功能
  • 一个图片的异步下载器
  • 一个内存 + 磁盘的缓存机制,并自动管理
  • gif动画支持
  • WebP格式支持
  • 后台解压图片
  • 确保同样地 URL 不会重复的下载多次
  • 确保无效的 URL 不会重复的链接
  • 确保主线程永远不会阻塞
  • 效果拔群!
  • 使用GCD以及要求ARC
  • 支持64位系统

以下进行SDWebImage使用的教程解说.

1. 从地址 https://github.com/rs/SDWebImage 下载源码,将源码包中得 SDWebImage 文件夹拖入你的工程当中.

2. 头文件较多,请新建一个 SDWebImage.h 的头文件,写以下代码并包含所有头文件,添加到.pch文件中

-------------------------------------------------------------------------------

//MKAnnotationView地图的注解View缓存
#import "MKAnnotationView+WebCache.h"

//判断NSData是否什么类型的图片(例如:jpg,png,gif)
#import "NSData+ImageContentType.h"

//是SDWebImage包的一部分
#import "SDImageCache.h"      //缓存相关
#import "SDWebImageCompat.h"  //组件相关
#import "SDWebImageDecoder.h" //解码相关

//图片下载以及下载管理器
#import "SDWebImageDownloader.h"
#import "SDWebImageDownloaderOperation.h"

//管理以及操作
#import "SDWebImageManager.h"
#import "SDWebImageOperation.h"

//UIButton类目
#import "UIButton+WebCache.h"

//gif类目
#import "UIImage+GIF.h"

//图片其他类目
#import "UIImage+MultiFormat.h"
#import "UIImage+WebP.h"
#import "UIImageView+WebCache.h"

-------------------------------------------------------------------------------

3. 正式开始讲解怎么使用

独立的下载图片的功能(没有缓存机制)

NSString *oneImageURL =
    @"http://wallpapers.wallbase.cc/rozne/wallpaper-573934.jpg";
    
    [[SDWebImageDownloader sharedDownloader] downloadImageWithURL:[NSURL URLWithString:oneImageURL]
                                                          options:0
     
     progress:^(NSInteger receivedSize, NSInteger expectedSize)
     {
         //此处为下载进度
     }
     completed:^(UIImage *image, NSData *data, NSError *error, BOOL finished)
     {
         //下载完成后进入这里执行
     }];

分析:此方法为单例模式,看其源码

+ (SDWebImageDownloader *)sharedDownloader {
    static dispatch_once_t once;
    static id instance;
    dispatch_once(&once, ^{
        instance = [self new];
    });
    return instance;
}

- (id)init {
    if ((self = [super init])) {
        _executionOrder = SDWebImageDownloaderFIFOExecutionOrder;
        _downloadQueue = [NSOperationQueue new];
        _downloadQueue.maxConcurrentOperationCount = 2;
        _URLCallbacks = [NSMutableDictionary new];
        _HTTPHeaders = [NSMutableDictionary dictionaryWithObject:@"image/webp,image/*;q=0.8" forKey:@"Accept"];
        _barrierQueue = dispatch_queue_create("com.hackemist.SDWebImageDownloaderBarrierQueue", DISPATCH_QUEUE_CONCURRENT);
        _downloadTimeout = 15.0;
    }
    return self;
}

typedef NS_ENUM(NSInteger, SDWebImageDownloaderExecutionOrder) {
    /**
     * Default value. All download operations will execute in queue style (first-in-first-out). 默认值.所有的下载操作将会进入串行线程池FIFO
     */
    SDWebImageDownloaderFIFOExecutionOrder,

    /**
     * All download operations will execute in stack style (last-in-first-out).
     */
    SDWebImageDownloaderLIFOExecutionOrder
};

如果仅仅看上面的部分,知道下载单例由串行线程池管理着,按照队列执行,一次最多能执行两个,但我在实际测试过程中发现,并不像描述的那样子......,好吧,就当做是并发执行的了(此处疑问有时间再解决)

独立的下载图片的功能(有缓存机制)

NSString *oneImageURL =
    @"http://pic.cnitblog.com/avatar/607542/20140226182241.png";
    
    [[SDWebImageManager sharedManager] downloadWithURL:[NSURL URLWithString:oneImageURL]
                                               options:0
     
    progress:^(NSInteger receivedSize, NSInteger expectedSize)
    {
        //此处为下载进度
    }
    completed:^(UIImage *image, NSError *error, SDImageCacheType cacheType, BOOL finished)
    {
        //下载完成后进入这里执行
    }];
清除缓存文件
    [[SDImageCache sharedImageCache] clearDisk];

判断本地缓存中是否存在网络中的图片
    NSString *imageNetURL = @"http://pic.cnitblog.com/avatar/607542/20140226182241.png";
    [[SDImageCache sharedImageCache] diskImageExistsWithKey:imageNetURL];

获取缓存图片张数
    [[SDImageCache sharedImageCache] getDiskCount];

获取所有缓存图片的总大小
    [[SDImageCache sharedImageCache] getSize];

直接从缓存中提取图片
    NSString *imageNetURL = @"http://pic.cnitblog.com/avatar/607542/20140226182241.png";
    [[SDImageCache sharedImageCache] imageFromDiskCacheForKey:imageNetURL];

直接删除缓存中得图片
   NSString *imageNetURL = @"http://pic.cnitblog.com/avatar/607542/20140226182241.png";
    [[SDImageCache sharedImageCache] removeImageForKey:imageNetURL];

在UITableView中使用
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
    {
        static NSString *MyIdentifier = @"Y.X.";
        
        UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:MyIdentifier];
        
        if (cell == nil)
        {
            cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault
                                           reuseIdentifier:MyIdentifier] autorelease];
        }
        
        // Here we use the new provided setImageWithURL: method to load the web image
        [cell.imageView setImageWithURL:[NSURL URLWithString:@"http://www.domain.com/path/to/image.jpg"]
                       placeholderImage:[UIImage imageNamed:@"placeholder.png"]];
        
        cell.textLabel.text = @"Y.X.";
        return cell;
    }

-未完待续-

版权声明:本文内容由阿里云实名注册用户自发贡献,版权归原作者所有,阿里云开发者社区不拥有其著作权,亦不承担相应法律责任。具体规则请查看《阿里云开发者社区用户服务协议》和《阿里云开发者社区知识产权保护指引》。如果您发现本社区中有涉嫌抄袭的内容,填写侵权投诉表单进行举报,一经查实,本社区将立刻删除涉嫌侵权内容。

相关文章
SDWebImage探究
SDWebImage探究(一)SDWebImage探究(二)SDWebImage探究(三)SDWebImage探究(四)SDWebImage探究(五)SDWebImage探究(六) —— 图片类型判断深入研究SDWebImage探究(七) —— 深入研...
986 0
Android应用开发中三种常见的图片压缩方法
版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/u010046908/article/details/52368551 Android应用开发中三种常见的图片压缩方法,分别是:质量压缩法、比例压缩法(根据路径获取图片并压缩)和比例压缩法(根据Bitmap图片压缩)。
897 0
开源框架:SDWebImage
http://blog.csdn.net/uxyheaven/article/details/7909373   SDWebImage是我搞iOS以来少数佩服的框架,膜拜一下作者.真的写的非常棒! 这套开源框架还是蛮重要的, 涉及到异步加载图片源和自动缓存.
838 0
iOS中 SDWebImage手动清除缓存的方法 技术分享
1.找到SDImageCache类 2.添加如下方法: - (float)checkTmpSize { float totalSize = 0; NSDirectoryEnumerator *fileEnumerator = [[NSFileManager def...
1034 0
Android应用开发-图片加载库Glide
Glide Picasso和Glide之间的区别: Picasso 仅仅缓存了全尺寸的图像;然而 Glide 缓存了原始图像,全分辨率图像和另外小版本的图像。
844 0
+关注
游贤明
文章
问答
视频
文章排行榜
最热
最新
相关电子书
更多
低代码开发师(初级)实战教程
立即下载
阿里巴巴DevOps 最佳实践手册
立即下载
冬季实战营第三期:MySQL数据库进阶实战
立即下载