您的位置:首页 > 理论基础 > 计算机网络

网络:NSURLSession 下载文件

2016-04-20 20:12 477 查看
#import "ViewController.h"
#import "SSZipArchive.h"
@interface ViewController ()

@end

@implementation ViewController

- (void)viewDidLoad {
[super viewDidLoad];
// Do any additional setup after loading the view, typically from a nib.
}

// 使用NSURLSession 下载,内存锋值不高。但是有些Xcode版本,峰值很6.3以前
// 但是在真机上不存在这个问题
- (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event {
// NSURL
NSURL *url = [NSURL URLWithString:@"http://localhost/ui.mp4"];
// Session发起请求
// location 文件下载完这后保存的路径
[[[NSURLSession sharedSession]downloadTaskWithURL:url completionHandler:^(NSURL * _Nullable location, NSURLResponse * _Nullable response, NSError * _Nullable error) {
NSLog(@"%@ -- %@",location.path, response);
// 下载完文件之后,文件被删除了
// 因为系统以为你下载的是压缩包,下载完成之后需要解压。解压完成之后,删除原文件
// 解压
/*
1. 压缩包的路径
2. 解压到的路径
*/
//        [SSZipArchive unzipFileAtPath:location.path toDestination:[NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES)lastObject]];

// 下载视频,需要解压吗 不需要
// 复制一份到另一个目录
NSFileManager *manager = [NSFileManager defaultManager];
// 保存文件的路径
NSString *fileName = [url.path lastPathComponent];
NSString *path = [[NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES)lastObject] stringByAppendingPathComponent:fileName];

// 把临时文件移动到缓存目录,并且改成我们需要的后缀名
NSLog(@"%@",path);
// 使用复制或者移动都可以
//        [manager moveItemAtPath:location.path toPath:path error:NULL];
[manager copyItemAtPath:location.path toPath:path error:NULL];
}] resume];
}

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