SDWebImage基础应用

本文介绍iOS中流行的第三方库SDWebImage的基本用法,包括异步加载图片、使用缓存提高加载速度、独立异步下载图片及内存警告时的缓存清理。

iOS中用到的异步加载图片最为广泛的三方库恐怕莫属SDWebImage了。下面记录一些自己使用到该库时候所用到的的基础用法,以后用到了方便来拿


1.最基础的异步加载图片方法,使用该方法,会把所加载的图片缓存到项目沙盒路径下

需导入头文件:#import "UIImageView+WebCache.h"

[cell.iconImageView sd_setImageWithURL:[NSURL URLWithString:urlString] placeholderImage:[UIImage imageNamed:@"ic_default_photo.png"]];

2.利用缓存措施,提高加载速度
需导入头文件:
#import
"SDWebImageManager.h"
#import "SDImageCache.h"

NSString *urlString = @"urlString";
UIImage *cacheImage = [[SDImageCache sharedImageCache] imageFromDiskCacheForKey:urlString];

    if (cacheImage) {
//如果从缓存中取出了缓存图片,则直接使用
       cell.iconImageView.image = cacheImage;
    } else {
//如果缓存中不存在缓存图片,则下载
       [[SDWebImageManager sharedManager] downloadImageWithURL:[NSURL URLWithString:urlString] options:SDWebImageProgressiveDownload progress:^(NSInteger receivedSize, NSInteger expectedSize) {
    //此处可以显示加载进度动画    
       } completed:^(UIImage *image, NSError *error, SDImageCacheType cacheType, BOOL finished, NSURL *imageURL) {
  //下载完成后使用,并把图片写入磁盘缓存,若仅把所加载的图片放到内存缓存,则 toDisk 传入参数:NO, 当然如果不需要显示进度等动画,该语句块中可用第一种方法代替。
         if (image) {
            //下载成功
            cell.iconImageView.image = image;
            [[SDImageCache sharedImageCache] storeImage:image forKey:urlString toDisk:YES];
         } else {
             //下载失败
             cell.iconImageView.image = [UIImage imageNamed:@"ic_default_photo.png"];
         }
   }

3.独立的异步图像下载
需导入头文件:#import "SDWebImageDownloader.h"

[[SDWebImageDownloader sharedDownloader] downloadImageWithURL:[NSURL URLWithString:@""] options:SDWebImageDownloaderProgressiveDownload progress:^(NSInteger receivedSize, NSInteger expectedSize) {
       
//此处可以显示加载进度动画
    }
completed:^(UIImage *image, NSData *data, NSError *error, BOOL finished) {
       
//your code here
    }];

4.当我们的应用受到内存警告时候,我们便需要进行一些适当的处理,在AppDelegate中的此方法中做清除图片缓存措施

需导入头文件:
#import 
"SDWebImageManager.h"

- (void)applicationDidReceiveMemoryWarning:(UIApplication *)application

{

    [[[SDWebImageManager sharedManager] imageCache] clearDisk];

    [[[SDWebImageManager sharedManager] imageCache] clearMemory];

}



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值