大文件下载
方案一:利用NSURLConnection和它的代理方法,及NSFileHandle(iOS9后不建议使用)
相关变量:
@property (nonatomic,strong) NSFileHandle *writeHandle;
@property (nonatomic,assign) long long totalLength;
1>发送请求
// 创建一个请求
NSURL *url = [NSURL URLWithString:@""];
NSURLRequest *request = [NSURLRequest requestWithURL:url];
// 使用NSURLConnection发起一个异步请求
[NSURLConnection connectionWithRequest:request delegate:self];
2>在代理方法中处理服务器返回的数据
/** 在接收到服务器的响应时调用下面这个代理方法
1.创建一个空文件
2.用一个句柄对象关联这个空文件,目的是方便在空文件后面写入数据
*/
- (void)connection:(NSURLConnection *)connection didReceiveResponse:(nonnull NSURLResponse *)response
{
// 创建文件路径
NSString *caches = [NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES)lastObject];
NSString *filePath = [caches stringByAppendingPathComponent:@"videos.zip"];
// 创建一个空的文件到沙盒中
NSFileManager *mgr = [NSFileManager defaultManager];
[mgr createFileAtPath:filePath contents:nil attributes:nil];
// 创建一个用来写数据的文件句柄
self.writeHandle = [NSFileHandle fileHandleForWritingAtPath:filePath];
// 获得文件的总大小
self.totalLength = response.expectedContentLength;
}
/** 在接收到服务器返回的文件数据时调用下面这个代理方法
利用句柄对象往文件的最后面追加数据
*/
- (void)connection:(NSURLConnection *)connection didReceiveData:(nonnull NSData *)data
{
// 移动到文件的最后面
[self.writeHandle seekToEndOfFile];
// 将数据写入沙盒
[self.writeHandle writeData:data];
}
/**
在所有数据接收完毕时,关闭句柄对象
*/
- (void)connectionDidFinishLoading:(NSURLConnection *)connection
{
// 关闭文件并清空
[self.writeHandle closeFile];
self.writeHandle = nil;
}
方案二:使用NSURLSession的NSURLSessionDownloadTask和NSFileManager
NSURLSession *session = [NSURLSession sharedSession];
NSURL *url = [NSURL URLWithString:@""];
// 可以用来下载大文件,数据将会存在沙盒里的tmp文件夹
NSURLSessionDownloadTask *task = [session downloadTaskWithURL:url completionHandler:^(NSURL * _Nullable location, NSURLResponse * _Nullable response, NSError * _Nullable error) {
// location :临时文件存放的路径(下载好的文件)
// 创建存储文件路径
NSString *caches = [NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES)lastObject];
// response.suggestedFilename:建议使用的文件名,一般跟服务器端的文件名一致
NSString *file = [caches stringByAppendingPathComponent:response.suggestedFilename];
/**将临时文件剪切或者复制到Caches文件夹
AtPath :剪切前的文件路径
toPath :剪切后的文件路径
*/
NSFileManager *mgr = [NSFileManager defaultManager];
[mgr moveItemAtPath:location.path toPath:file error:nil];
}];
[task resume];










