//
// ViewController.m
// NSURLSession代理简介 #import "ViewController.h" @interface ViewController ()<NSURLSessionDataDelegate> @end @implementation ViewController - (void)viewDidLoad {
[super viewDidLoad]; }
//这是为了测试而建立的点击屏幕事件。
-(void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event{ //代理 测试 NSURL * url = [NSURL URLWithString:@"http://localhost/login.php?username=haha&password=123"]; //创建自定义Session NSURLSession * session = [NSURLSession sessionWithConfiguration:[NSURLSessionConfiguration defaultSessionConfiguration] delegate:self delegateQueue:[[NSOperationQueue alloc]init]]; NSURLSessionTask * task = [session dataTaskWithURL:url];
//开启任务
[task resume]; }
#pragma mark - deleDate
//接受到服务器响应
-(void)URLSession:(NSURLSession *)session dataTask:(NSURLSessionDataTask *)dataTask didReceiveResponse:(NSURLResponse *)response completionHandler:(void (^)(NSURLSessionResponseDisposition))completionHandler
{
//__FUNCTION__ c语言字符串用s
NSLog(@"%s",__FUNCTION__); //允许服务器回传数据
completionHandler(NSURLSessionResponseAllow); }
//接受服务器回传的数据可能执行多次
-(void)URLSession:(NSURLSession *)session dataTask:(NSURLSessionDataTask *)dataTask didReceiveData:(NSData *)data{ NSLog(@"%@",[[NSString alloc]initWithData:data encoding:NSUTF8StringEncoding]); }
//请求成功或者失败
-(void)URLSession:(NSURLSession *)session didBecomeInvalidWithError:(NSError *)error{
NSLog(@"%@",error);
}
@end
上面简单介绍了一下
然后我们来看一个demo
其中下载文件的地址,读者可以自己配置
//
// ViewController.m
// NSURLSession大文件下载
//
// #import "ViewController.h" @interface ViewController ()<NSURLSessionDownloadDelegate> @property (nonatomic, strong) NSURLSessionDownloadTask * task; @property (nonatomic, strong) NSData * resumeData; @property (nonatomic, strong) NSURLSession * session; @end @implementation ViewController - (IBAction)start:(id)sender { NSURLSession * session = [NSURLSession sessionWithConfiguration:[NSURLSessionConfiguration defaultSessionConfiguration] delegate:self delegateQueue:[[NSOperationQueue alloc] init]]; self.session = session; self.task = [session downloadTaskWithURL:[NSURL URLWithString:[@"http://192.168.1.200/DOM解析.mp4"stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]]]; [self.task resume];
} - (IBAction)pause:(id)sender { //暂停就是将任务挂起 [self.task cancelByProducingResumeData:^(NSData * _Nullable resumeData) { //保存已下载的数据
self.resumeData = resumeData;
}];
} - (IBAction)resume:(id)sender { //可以使用ResumeData创建任务 self.task = [self.session downloadTaskWithResumeData:self.resumeData]; //开启继续下载
[self.task resume]; } - (void)viewDidLoad {
[super viewDidLoad];
// Do any additional setup after loading the view, typically from a nib. NSLog(@"%@",NSSearchPathForDirectoriesInDomains(, , ));
} /* 监测临时文件下载的数据大小,当每次写入临时文件时,就会调用一次 bytesWritten 单次写入多少
totalBytesWritten 已经写入了多少
totalBytesExpectedToWrite 文件总大小 */ - (void)URLSession:(NSURLSession *)session downloadTask:(NSURLSessionDownloadTask *)downloadTask
didWriteData:(int64_t)bytesWritten
totalBytesWritten:(int64_t)totalBytesWritten
totalBytesExpectedToWrite:(int64_t)totalBytesExpectedToWrite { //打印下载百分比
NSLog(@"%f",totalBytesWritten * 1.0 / totalBytesExpectedToWrite); } //下载完成 - (void)URLSession:(NSURLSession *)session downloadTask:(NSURLSessionDownloadTask *)downloadTask
didFinishDownloadingToURL:(NSURL *)location { NSString * cachesPath = [[NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES) lastObject] stringByAppendingPathComponent:downloadTask.response.suggestedFilename]; NSFileManager * mgr = [NSFileManager defaultManager]; [mgr moveItemAtURL:location toURL:[NSURL fileURLWithPath:cachesPath] error:NULL]; } - (void)URLSession:(NSURLSession *)session task:(NSURLSessionTask *)task didCompleteWithError:(NSError *)error { NSLog(@"%@",error);
} - (void)didReceiveMemoryWarning {
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
} @end