@interface AAAViewController ()<NSURLSessionDataDelegate>
/**
NSFileHandle 文件句柄
特点:在写数据的时候边写边移动位置
使用步骤:
1> 创建空的文件
2> 创建文件句柄指针 指向该文件
3> 当接收到数据的时候,使用该句柄来写数据
4> 当所有的数据写完,应该关闭句柄指针
*/
@property(nonatomic, strong)NSFileHandle *fileHandle;
@property(nonatomic, assign)long long totalSize;
@property(nonatomic, assign)long long currentSize;
@end
@implementation AAAViewController
-(void)download:(NSString *)urlStr{
// 1 创建URL
NSURL *url = [NSURL URLWithString:urlStr];
//2. 创建请求
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
// POST 请求才设置
// //3. 设置请求的方式
// request.HTTPMethod = @"POST";
// //4. 设置请求体
// request.HTTPBody =data;
//5. 创建sesstion
NSURLSessionConfiguration *config = [[NSURLSessionConfiguration alloc] init];
NSURLSession *session = [NSURLSession sessionWithConfiguration:config
delegate:self
delegateQueue:[[NSOperationQueue alloc] init]];
//6. 创建下载任务
NSURLSessionDataTask *dataTask = [session dataTaskWithRequest:request];
[dataTask resume];
}
#pragma mark- NSURLSessionDataDelegate
//1. 接收到响应头就会响应
-(void)URLSession:(NSURLSession *)session
dataTask:(NSURLSessionDataTask *)dataTask
didReceiveResponse:(NSURLResponse *)response
completionHandler:(void (^)(NSURLSessionResponseDisposition))completionHandler{
//1. 获取文件建议名称
NSString *suggestName = [response suggestedFilename]; // 文件建议的名称,URL 的最后一个节点
NSString *cachepath = @"usr/default/";
NSString *fullPath = [NSString stringWithFormat:@"%@/%@",cachepath,suggestName];
//创建一个空的文件
[[NSFileManager defaultManager] createFileAtPath:fullPath contents:nil attributes:nil];
//2. 创建文件句柄
self.fileHandle = [NSFileHandle fileHandleForWritingAtPath:fullPath];
//2. 获取下载文件总大小
self.totalSize = [response expectedContentLength];
/**
NSURLSessionResponseCancel // 取消请求
NSURLSessionResponseAllow // 接收数据
NSURLSessionResponseBecomeDownload //
NSURLSessionResponseBecomeStream //
*/
completionHandler(NSURLSessionResponseAllow);
}
//2. 接收到数据就会调用
-(void)URLSession:(NSURLSession *)session
dataTask:(NSURLSessionDataTask *)dataTask
didReceiveData:(NSData *)data{
// 不断的拼接服务器返回的数据
[self.fileHandle writeData:data];
self.currentSize += data.length;
CGFloat progress = 1.0 *self.currentSize / self.totalSize;
NSLog(@"当前下载进度: %f",progress);
}
//3. 下载完成或者是失败就会调用
-(void)URLSession:(NSURLSession *)session
task:(nonnull NSURLSessionTask *)task
didCompleteWithError:(nullable NSError *)error{
if (error == nil) {
// 得到请求的响应头信息
[self.fileHandle closeFile];
}
}
@end
网友评论