您的位置:首页 > 其它

NSURLSession实现图片下载

2016-02-04 13:22 375 查看
本文主要介绍使用NSURLSession来实现图片下载,分别是带缓存的下载和无缓存下载

1.带缓存下载

NSMutableURLRequest * request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:[self preventNotRecognizedCharactersWithUrl:url]] cachePolicy:NSURLRequestUseProtocolCachePolicy timeoutInterval:30.0];

NSURLSession * session = [NSURLSession sharedSession];

NSURLSessionDownloadTask * downloadTask = [session downloadTaskWithRequest:request completionHandler:^(NSURL * _Nullable location, NSURLResponse * _Nullable response, NSError * _Nullable error) {
NSLog(@"%@", response);
NSLog(@"%@", response.suggestedFilename);
NSLog(@"%@", location.description);
NSString * locationPath = [location.absoluteString substringFromIndex:7];
if (!error) {
NSString * cachePath = [self saveImageFileUrl];
NSString * fileName = response.suggestedFilename;
//缓存文件夹路劲
NSString * savePath = [cachePath stringByAppendingPathComponent:fileName];
NSURL * saveUrl = [NSURL fileURLWithPath:savePath];
NSError * saveError;

//判断下载的文件与缓存的是否一样,如果一样,使用缓存文件,如果不一样,替换或转移缓存文件

if ([[NSFileManager defaultManager] contentsEqualAtPath:locationPath andPath:savePath]) {
dispatch_async(dispatch_get_main_queue(), ^{
imageView.image = [UIImage imageWithContentsOfFile:savePath];
});
}else{
//将tmp文件夹中的临时文件重命名后转移到缓存文件夹中
[[NSFileManager defaultManager] copyItemAtURL:location toURL:saveUrl error:&saveError];
if (!saveError) {
dispatch_async(dispatch_get_main_queue(), ^{
imageView.image = [UIImage imageWithContentsOfFile:savePath];
});
}
}
}else{
NSLog(@"%@", error.localizedDescription);
}
}];
[downloadTask resume];


2.不带缓存下载

NSMutableURLRequest * request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:[self preventNotRecognizedCharactersWithUrl:url]] cachePolicy:NSURLRequestUseProtocolCachePolicy timeoutInterval:30.0];

NSURLSession * session = [NSURLSession sharedSession];

NSURLSessionDownloadTask * downloadTask = [session downloadTaskWithRequest:request completionHandler:^(NSURL * _Nullable location, NSURLResponse * _Nullable response, NSError * _Nullable error) {
NSLog(@"%@", response);
if (!error) {
dispatch_async(dispatch_get_main_queue(), ^{
//无缓存下载图片
NSData * imageData = [NSData dataWithContentsOfURL:location];
imageView.image = [UIImage imageWithData:imageData];
});
}else{
NSLog(@"%@", error.localizedDescription);
}
}];
[downloadTask resume];


上文中的自定义方法

//沙盒图片存储路劲
+(NSString *)saveImageFileUrl{
NSString * imageUrl = [[NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES) lastObject] stringByAppendingString:@"/images"];

NSFileManager *fileManager = [[NSFileManager alloc] init];
// 判断文件夹是否存在,如果不存在,则创建
if (![[NSFileManager defaultManager] fileExistsAtPath:imageUrl]) {
[fileManager createDirectoryAtPath:imageUrl withIntermediateDirectories:YES attributes:nil error:nil];
}
NSLog(@"%@", imageUrl);
return imageUrl;
}

//防止不被承认的字符
+(NSString *)preventNotRecognizedCharactersWithUrl:(NSString *)url{
if (DeviceVersion >= 9.0) {
//对url进行编译不被承认的字符(ios9 中新出的方法,替代[urlStr stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];)
url = [url stringByAddingPercentEncodingWithAllowedCharacters:[NSCharacterSet URLQueryAllowedCharacterSet]];
}else{
url = [url stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
}
return url;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: