NSURLSession
NSMutableURLRequest * request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:@"http://xxxx.long.xlx"]];
request.HTTPMethod = @"POST";
request.HTTPBody = [@"username=lee&pwd=123" dataUsingEncoding:NSUTF8StringEncoding];
NSURLSessionDataTask * task = [[NSURLSession sharedSession]dataTaskWithRequest:request completionHandler:^(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error) {
}];
[task resume];
NSURLSessionDownloadTask * task = [[NSURLSession sharedSession]downloadTaskWithURL:[NSURL URLWithString:@""] completionHandler:^(NSURL * _Nullable location, NSURLResponse * _Nullable response, NSError * _Nullable error) {
}];
[task resume];
//文件已下载的长度
#define DownloadLength [[[NSFileManager defaultManager]attributesOfItemAtPath:Mp4File error:nil][NSFileSize] integerValue]
//所需要下载文件的URL
#define FileUrl @"http://120.25.226.186:32812/resources/videos/minion_02.mp4"
//沙盒中的文件名
#define FileName FileUrl.md5String
//文件的存放路径
#define Mp4File [[NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES) lastObject] stringByAppendingPathComponent:FileName]
//存放文件总长度的文件路径
#define TotalLengthPath [[NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES) lastObject] stringByAppendingPathComponent:@"totalLength.xmg"]
- 开启任务
NSURLSession * session = [NSURLSession sessionWithConfiguration:[NSURLSessionConfiguration defaultSessionConfiguration] delegate:self delegateQueue:[[NSOperationQueue alloc]init]];
//设置请求头(告诉服务器从第1024个字节下载)
[request setValue:@"bytes=1024-" forHTTPHeaderField:@"Range"];
NSURLSessionDataTask * task = [session dataTaskWithRequest:request];
[task resume];
- 实现代理方法
#pragma mark - <NSURLSessionDataDelegate>
//1.接受到相应
- (void)URLSession:(NSURLSession *)session dataTask:(NSURLSessionDataTask *)dataTask didReceiveResponse:(nonnull NSHTTPURLResponse *)response completionHandler:(nonnull void (^)(NSURLSessionResponseDisposition))completionHandler
{
//打开接收流
[self.stream open];
//获得服务器本次请求文件返回的总长度
self.contentLength = [response.allHeaderFields[@"Content-Length"] integerValue] + DownloadLength;
//存储总长度
NSMutableDictionary * dict = [NSMutableDictionary dictionaryWithContentsOfFile:TotalLengthPath];
if (dict == nil) dict = [NSMutableDictionary dictionary];
dict[FileName] = @(self.contentLength);
[dict writeToFile:TotalLengthPath atomically:YES];
//接收这个请求,允许接受服务器数据 (只有调用这个方法才会调用2.方法)
completionHandler(NSURLSessionResponseAllow);
}
//2.接受服务器返回的数据 这个方法可能会调用多次
- (void)URLSession:(NSURLSession *)session dataTask:(NSURLSessionDataTask *)dataTask didReceiveData:(NSData *)data
{
//写入数据
[self.stream write:data.bytes maxLength:data.length];
//获得目前下载文件长度
NSInteger downloadLength = (NSInteger)[[NSFileManager defaultManager]attributesOfItemAtPath:Mp4File error:nil][NSFileSize];
//下载进度
NSLog(@"%f",1.0*(downloadLength/self.contentLength));
}
//3.请求完毕(成功/失败)
- (void)URLSession:(NSURLSession *)session task:(nonnull NSURLSessionTask *)task didCompleteWithError:(nullable NSError *)error
{
//关闭流
[self.stream close];
self.stream = nil;
//清除任务
self.task = nil;
}
网友评论