一: NSURLSession简介

1.实施步骤

1.1 使用 NSURLSession对象 创建TASK ,然后执行TASK

2.TASK的类型:

2016 - 1 - 24 NSURLSession  (一)-LMLPHP

二: NSURLSession的简单使用:

- (void)download{
NSURL*url = [NSURL URLWithString:@"http://120.25.226.186:32812/resources/images/minion_15.png"]; // NSURLRequest *request = [NSURLRequest requestWithURL:url]; NSURLSession *session = [NSURLSession sharedSession]; // 创建TASK 下载到location中
NSURLSessionDownloadTask *tast = [session downloadTaskWithURL:url completionHandler:^(NSURL * _Nullable location, NSURLResponse * _Nullable response, NSError * _Nullable error) {
NSLog(@"%s",__func__);
NSFileManager *fileManger = [NSFileManager defaultManager]; // 设置下载的文件路径和文件名
NSString *file = [[NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES) lastObject] stringByAppendingString:response.suggestedFilename];
[fileManger moveItemAtURL:location toURL:[NSURL fileURLWithPath:file] error:nil];
NSLog(@"%@",file);
}];
[tast resume];
}

三: NSURLSession 的代理

需要注意在接受到响应的代理方法中设置允许处理服务器响应

- (void)delegate{
NSURL*url = [NSURL URLWithString:@"http://120.25.226.186:32812/resources/images/minion_15.png"];
// NSURLRequest *request = [NSURLRequest requestWithURL:url]; // Configuration 配置外形
NSURLSession *session = [NSURLSession sessionWithConfiguration:[NSURLSessionConfiguration defaultSessionConfiguration] delegate:self delegateQueue:[[NSOperationQueue alloc] init]]; NSURLSessionDataTask *task = [session dataTaskWithURL:url]; [task resume]; }
// 接收到到相应调用的代理方法
- (void)URLSession:(NSURLSession *)session dataTask:(NSURLSessionDataTask *)dataTask didReceiveResponse:(NSURLResponse *)response completionHandler:(void (^)(NSURLSessionResponseDisposition))completionHandler{// Dispositon 处置 NSLog(@"%s",__func__);
// 允许处理服务器相应,
completionHandler(NSURLSessionResponseAllow); }
- (void)URLSession:(NSURLSession *)session dataTask:(NSURLSessionDataTask *)dataTask didReceiveData:(NSData *)data{
NSLog(@"%s",__func__); }
- (void)URLSession:(NSURLSession *)session task:(NSURLSessionTask *)task didCompleteWithError:(NSError *)error{
NSLog(@"'%@",error);
NSLog(@"%s",__func__); }
05-08 08:06