NSURLSession实现图片下载
2016-02-04 13:22
375 查看
本文主要介绍使用NSURLSession来实现图片下载,分别是带缓存的下载和无缓存下载
1.带缓存下载
2.不带缓存下载
上文中的自定义方法
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; }
相关文章推荐
- LeetCode 22. Generate Parentheses(构造)
- C#成神之路<9> C#引用数据类型扩展
- 【Android】3.6 地图基本控制方法
- window mysql安装步骤
- servlet复习(五)cookie管理
- MYSQL建立索引需要注意几点
- ZOJ 1002:Fire Net
- 哈理工OJ 1692【水题】
- [LeetCode] Longest Substring Without Repeating Characters (LinkedHashSet的妙用)
- [C++]string中文的匹配问题
- 文本文件与字符编码
- 轻蔑这个,鄙视那个,眼高手低,好高骛远,有点料就忍不住到处兜售
- torch学习笔记(二)
- 利用51单片机制作廉价盒仔机器人
- order by多个字段对索引的影响
- C 语言结构体定义 使用
- HDU 1045:Fire Net
- 【贪心】[BZOJ1034]泡泡堂BNB
- Eclipse+Maven创建webapp项目
- 不要随随便便的distinct和order by