您的位置:首页 > 移动开发 > IOS开发

iOS异步加载缓存图片

2015-10-08 18:50 405 查看
- (void)viewDidLoad {
[super
viewDidLoad];

imageView = [[UIImageView
alloc] init];

[imageView
setBackgroundColor:[UIColor
grayColor]];

imageView.frame =
CGRectMake(60,
60, 200,
200);

[self.view
addSubview:imageView];

NSOperationQueue *operationQueue = [[NSOperationQueue
alloc] init];

NSInvocationOperation *op = [[NSInvocationOperation
alloc] initWithTarget:self
selector:@selector(downloadImage)
object:nil];

[operationQueue
addOperation:op];

}

- (void)downloadImage {
NSArray *paths =
NSSearchPathForDirectoriesInDomains(NSCachesDirectory,
NSUserDomainMask, YES);

NSString *diskCachePath = [[paths
objectAtIndex:0]
stringByAppendingPathComponent:@"imageCache"];

//如果目录imageCache不存在,创建目录
if (![[NSFileManager
defaultManager] fileExistsAtPath:diskCachePath]) {


NSError *error=nil;

[[NSFileManager
defaultManager] createDirectoryAtPath:diskCachePath
withIntermediateDirectories:YES
attributes:nil
error:&error];

}
NSString *localPath = [NSString
stringWithFormat:@"%@/headimage.png",diskCachePath];


//如果有缓存图片,直接读取cache内的缓存图片
if ([[NSFileManager
defaultManager] fileExistsAtPath:localPath]) {


NSData *data = [NSData
dataWithContentsOfFile:localPath];


dispatch_async(dispatch_get_main_queue(), ^{


imageView.image = [UIImage
imageWithData:data];

});
}
else{

NSURL *imagePathUrl = [NSURL
URLWithString:@"http://s15.sinaimg.cn/middle/9914f9fdhbc6170891ebe&690.png"];


NSData *data = [NSData
dataWithContentsOfURL:imagePathUrl];


dispatch_async(dispatch_get_main_queue(), ^{


imageView.image = [UIImage
imageWithData:data];

});
[data
writeToFile:localPath atomically:YES];

}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: