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 "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
// 此处可以显示加载进度动画
} completed :^( UIImage *image, NSData *data, NSError *error, BOOL finished) {
//your code here
}];
需导入头文件:
#import "SDWebImageManager.h"
- (void)applicationDidReceiveMemoryWarning:(UIApplication *)application
{
[[[SDWebImageManager sharedManager] imageCache] clearDisk];
[[[SDWebImageManager sharedManager] imageCache] clearMemory];
}