NSURLSession下载

//会话模式作用与NSURLConnection基本一致

//三种会话模式: default   ephemeral  background

NSURLSessionConfiguration *configuration = [NSURLSessionConfiguration defaultSessionConfiguration];

//NSURLSession:会话

//创建会话

//三种创建方式

//1.[NSURLSession sharedSession]

//2.[NSURLSession sessionWithConfiguration:<#(nonnull NSURLSessionConfiguration *)#>]

//3.

//1.设置会话模式 1.3 delegateQueue :规定任务completionHandler的block块是在哪个线程执行,如果是nil,那么completionHandler在系统开辟的分线程中执行3

//1.2 delegate:可以为nil,数据是任务中的block块如果为self,要导入协议,数据在协议方法里

NSURLSession *session = [NSURLSession sessionWithConfiguration:configuration delegate:self delegateQueue:nil];

//路径

NSURL*url = [NSURL URLWithString:@"http://localhost:8080/Login1/NewServlet?command=5"];

//创建任务(block的回调比代理有更高的优先级)如果设置了completionHandler,那么无论有没有实现代理,我们的响应数据都是从completionHandler返回,也就是说completionHandler有更高的优先级,如果completionHandler为nil则数据从代理方法中返回(需要导入3个协议)

//    NSURLSessionDataTask *task = [session dataTaskWithURL:url completionHandler:^(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error) {

//        NSLog(@"data ----> %@",[[NSString alloc]initWithData:data encoding:NSUTF8StringEncoding]);

//        NSLog(@"currentThread is ---->%@",[NSThread currentThread]);

//    }];

NSURLSessionDataTask *task = [session dataTaskWithURL:url];

//执行任务

[task resume];

}

#pragma mark -- NSURLSessionDelegate,NSURLSessionDataDelegate,NSURLSessionTaskDelegate

//接收到服务器响应时调用

- (void)URLSession:(NSURLSession *)session dataTask:(nonnullNSURLSessionDataTask *)dataTask didReceiveResponse:(nonnullNSURLResponse *)response completionHandler:(nonnullvoid(^)(NSURLSessionResponseDisposition))completionHandler {

NSLog(@"接收响应");

//接收到响应后需要设置继续执行的操作

//继续执行响应NSURLSessionResponseAllow 4

completionHandler(NSURLSessionResponseAllow);

}

//接收到服务器返回的数据时调用可能返回多次

- (void)URLSession:(NSURLSession *)session dataTask:(nonnullNSURLSessionDataTask *)dataTask didReceiveData:(nonnullNSData *)data {

NSLog(@"接收到数据");

NSLog(@"delegate data -----> %@",[[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding]);

}

//响应完成时调用

- (void)URLSession:(NSURLSession *)session task:(nonnullNSURLSessionTask *)task didCompleteWithError:(nullableNSError *)error {

NSLog(@"响应完成");

//关闭会话

[session finishTasksAndInvalidate];

}

//关闭会话调用

- (void)URLSession:(NSURLSession *)session didBecomeInvalidWithError:(NSError *)error {

NSLog(@"关闭会话");

}

你可能感兴趣的:(NSURLSession下载)