一、NSURLSession的基本用法

 //
// ViewController.m
// NSURLSession
//
// Created by ma c on 16/2/1.
// Copyright © 2016年 博文科技. All rights reserved.
// #import "ViewController.h" @interface ViewController ()<NSURLSessionDownloadDelegate> @end @implementation ViewController
/*
任务:任何请求都是一个任务 NSURLSessionDataTask:普通的GET、POST请求
NSURLSessionDownloadTask:文件下载
NSURLSessionUploadTask:文件上传 注意:如果给下载任务设置了completionHandler这个block,也实现了下载代理方法,优先执行block */
- (void)viewDidLoad {
[super viewDidLoad]; self.view.backgroundColor = [UIColor cyanColor]; } - (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event
{
// [self sendGetRequest];
// [self sendPostRequest];
// [self downlaodTask1];
[self downlaodTask2];
} #pragma mark - NSURLSessionDownloadTask2
///下载任务(有下载进度)
- (void)downlaodTask2
{
//1.创建Session对象
NSURLSessionConfiguration *cfg = [NSURLSessionConfiguration defaultSessionConfiguration];
NSURLSession *session = [NSURLSession sessionWithConfiguration:cfg delegate:self delegateQueue:[NSOperationQueue mainQueue]];
//2.创建一个任务
NSURL *url = [NSURL URLWithString:@"http://localhost:8080/MJServer/resources/videos/minion_02.mp4"];
NSURLSessionDownloadTask *task = [session downloadTaskWithURL:url];
//3.开始任务
[task resume];
} #pragma mark - NSURLSessionDownloadDelegate的代理方法
///下载完毕时调用
- (void)URLSession:(NSURLSession *)session downloadTask:(NSURLSessionDownloadTask *)downloadTask didFinishDownloadingToURL:(NSURL *)location
{
NSLog(@"didFinishDownloadingToURL--->%@",location);
//location:文件的临时路径,下载好的文件
NSString *caches = [NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, nil) lastObject];
NSString *file = [caches stringByAppendingPathComponent:downloadTask.response.suggestedFilename]; //降临时文件夹,剪切或者复制到Caches文件夹
NSFileManager *mgr = [NSFileManager defaultManager];
[mgr moveItemAtPath:location.path toPath:file error:nil];
}
///恢复下载时调用
- (void)URLSession:(NSURLSession *)session downloadTask:(NSURLSessionDownloadTask *)downloadTask didResumeAtOffset:(int64_t)fileOffset expectedTotalBytes:(int64_t)expectedTotalBytes
{ }
///每当写完一部分就调用(根据文件大小调用多次)
//bytesWritten: 这次调用写了多少
//totalBytesWritten: 累计写了多少长度到沙河中
//totalBytesExpectedToWrite:文件的总长度
- (void)URLSession:(NSURLSession *)session downloadTask:(NSURLSessionDownloadTask *)downloadTask didWriteData:(int64_t)bytesWritten totalBytesWritten:(int64_t)totalBytesWritten totalBytesExpectedToWrite:(int64_t)totalBytesExpectedToWrite
{
double progress = (double)totalBytesWritten / totalBytesExpectedToWrite; NSLog(@"下载进度--->%lf",progress); } #pragma mark - NSURLSessionDownloadTask1
///下载任务(不能看到下载进度)
- (void)downlaodTask1
{
//1.创建Session对象
NSURLSession *session = [NSURLSession sharedSession];
//2.创建NSURL
NSURL *url = [NSURL URLWithString:@"http://localhost:8080/MJServer/resources/videos/minion_02.mp4"];
NSURLSessionDownloadTask *task = [session downloadTaskWithURL:url completionHandler:^(NSURL * _Nullable location, NSURLResponse * _Nullable response, NSError * _Nullable error) {
//location:文件的临时路径,下载好的文件
NSString *caches = [NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, nil) lastObject];
NSString *file = [caches stringByAppendingPathComponent:response.suggestedFilename]; //降临时文件夹,剪切或者复制到Caches文件夹
NSFileManager *mgr = [NSFileManager defaultManager];
[mgr moveItemAtPath:location.path toPath:file error:nil]; //[mgr copyItemAtPath:location.path toPath:file error:nil]; }];
//3.开始任务
[task resume];
} #pragma mark - NSURLSessionDataTask
///POST请求
- (void)sendPostRequest
{
//1.创建Session对象
NSURLSession *session = [NSURLSession sharedSession]; //2.创建NSURL
NSURL *url = [NSURL URLWithString:@"http://localhost:8080/MJServer/login"];
//3.创建请求
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
request.HTTPMethod = @"POST";
//4.设置请求体
request.HTTPBody = [@"username=123&pwd=123" dataUsingEncoding:NSUTF8StringEncoding];
//5.创建一个任务
NSURLSessionDataTask *task = [session dataTaskWithRequest:request completionHandler:^(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error) { NSDictionary *dict = [NSJSONSerialization JSONObjectWithData:data
options:NSJSONReadingMutableLeaves error:nil];
NSLog(@"sendPostRequest:%@",dict);
}];
//6.开始任务
[task resume];
} ///GET请求
- (void)sendGetRequest
{
//1.得到session对象
NSURLSession *session = [NSURLSession sharedSession];
//2.创建一个任务
NSURL *url = [NSURL URLWithString:@"http://localhost:8080/MJServer/video"];
NSURLSessionDataTask *task = [session dataTaskWithURL:url completionHandler:^(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error) { NSDictionary *dict = [NSJSONSerialization JSONObjectWithData:data
options:NSJSONReadingMutableLeaves error:nil];
NSLog(@"sendGetRequest:%@",dict);
}];
//3.开始任务
[task resume];
}
@end

二、NSURLSession的断点续传

 //
// ViewController.m
// IOS_0204_NSURLSession断点续传
//
// Created by ma c on 16/2/4.
// Copyright © 2016年 博文科技. All rights reserved.
// #import "ViewController.h" @interface ViewController ()<NSURLSessionDownloadDelegate> - (IBAction)btnClick:(UIButton *)sender;
@property (weak, nonatomic) IBOutlet UIButton *btnClick;
@property (weak, nonatomic) IBOutlet UIProgressView *progressView; @property (nonatomic, strong) NSURLSessionDownloadTask *task;
@property (nonatomic, strong) NSData *resumeData;
@property (nonatomic, strong) NSURLSession *session; @end @implementation ViewController - (void)viewDidLoad {
[super viewDidLoad]; self.progressView.progress = 0.01;
} - (NSURLSession *)session
{
if (!_session) {
//获得session
NSURLSessionConfiguration *cfg = [NSURLSessionConfiguration defaultSessionConfiguration];
_session = [NSURLSession sessionWithConfiguration:cfg delegate:self delegateQueue:[NSOperationQueue mainQueue]];
}
return _session;
} - (IBAction)btnClick:(UIButton *)sender {
//取反
sender.selected = !sender.isSelected; if (sender.selected) { //开始、恢复下载 if (self.resumeData) { //恢复下载
[self resume]; } else { //开始下砸
[self start];
} } else { //暂停下载
[self pause];
}
}
//从零开始下载
- (void)start
{
//1.创建一个下载任务
NSURL *url = [NSURL URLWithString:@"http://localhost:8080/MJServer/resources/videos/minion_01.mp4"];
self.task = [self.session downloadTaskWithURL:url];
//2.开始任务
[self.task resume];
}
//继续下载
- (void)resume
{
//传入上次暂停下载返回的数据,就可以恢复下载
self.task = [self.session downloadTaskWithResumeData:self.resumeData]; [self.task resume];
}
//暂停下载
- (void)pause
{
__weak typeof(self) vc = self;
[self.task cancelByProducingResumeData:^(NSData * _Nullable resumeData) { //resumeData:包含了下载的开始位置
vc.resumeData = resumeData;
vc.task = nil; }];
}
#pragma mark - NSURLSessionDownloadDelegate的代理方法
- (void)URLSession:(NSURLSession *)session downloadTask:(NSURLSessionDownloadTask *)downloadTask didFinishDownloadingToURL:(NSURL *)location
{
self.btnClick.selected = !self.btnClick.isSelected; NSString *caches = [NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES) lastObject];
//suggestedFilename建议使用的文件名,一般与服务器端的文件名一致
NSString *file = [caches stringByAppendingPathComponent:downloadTask.response.suggestedFilename];
//NSLog(@"%@",file);
NSFileManager *mgr = [NSFileManager defaultManager];
//将临时文件复制或者剪切到caches文件夹
[mgr moveItemAtPath:location.path toPath:file error:nil]; } - (void)URLSession:(NSURLSession *)session downloadTask:(NSURLSessionDownloadTask *)downloadTask didResumeAtOffset:(int64_t)fileOffset expectedTotalBytes:(int64_t)expectedTotalBytes
{ } - (void)URLSession:(NSURLSession *)session downloadTask:(NSURLSessionDownloadTask *)downloadTask didWriteData:(int64_t)bytesWritten totalBytesWritten:(int64_t)totalBytesWritten totalBytesExpectedToWrite:(int64_t)totalBytesExpectedToWrite
{
//获得下载进度
self.progressView.progress = (double)totalBytesWritten / totalBytesExpectedToWrite;
}
@end
 
05-02 21:56