NSURLSession是xcode7.0之后的请求网络的新API,是代替NSURLConnection的。在2013年苹果的技术发布会上首次提出,xcode7.0后正式废除NSURLConnection方法。
不同于NSURLConnection需要设置同步异步请求,NSURLSession是自动创建子线程来进行网络请求,所以要在回调方法中需要用主线程刷新。
而且NSURLSession支持后台网络操作。可以实现下载数据到内存,下载数据到文件系统,上传到服务器,断点续传,下载任务跟进以及在后台完成上述方法。
NSURL *fileURL = [[NSBundle mainBundle] URLForResource:@"sad" withExtension:nil];
NSURL *url = [NSURL URLWithString:@"12"];
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
//请求模式设为PUT 文件大小无限制,可以覆盖文件
request.HTTPMethod = @"PUT";
NSString *authStr = @"admin:sadadssa";
NSData *data = [authStr dataUsingEncoding:NSUTF8StringEncoding];
NSString *base64Str = [data base64EncodedStringWithOptions:0];
NSString *resultStr = [NSString stringWithFormat:@"Basic %@",base64Str];
[request setValue:resultStr forKey:@"Authorization"];
NSURLSessionConfiguration *configuration = [NSURLSessionConfiguration defaultSessionConfiguration];
//设置本类为代理,创建子队列
NSURLSession *session = [NSURLSession sessionWithConfiguration:configuration delegate:self delegateQueue:[[NSOperationQueue alloc]init]];
//设置监听任务
NSURLSessionUploadTask *task = [session uploadTaskWithRequest:request fromFile:fileURL];
[task resume];
#pragma mark - 上传进度的代理方法
- (void)URLSession:(NSURLSession *)session task:(NSURLSessionTask *)task didSendBodyData:(int64_t)bytesSent totalBytesSent:(int64_t)totalBytesSent totalBytesExpectedToSend:(int64_t)totalBytesExpectedToSend
{
// bytesSent totalBytesSent totalBytesExpectedToSend
// 发送字节(本次发送的字节数) 总发送字节数(已经上传的字节数) 总希望要发送的字节(文件大小)
NSLog(@"%lld-%lld-%lld-", bytesSent, totalBytesSent, totalBytesExpectedToSend);
// 已经上传的百分比
float progress = (float)totalBytesSent / totalBytesExpectedToSend;
NSLog(@"%f", progress);
}
#pragma mark - 上传完成的代理方法
- (void)URLSession:(NSURLSession *)session task:(NSURLSessionTask *)task didCompleteWithError:(NSError *)error
{
NSLog(@"完成 %@", [NSThread currentThread]);
}
@end
//请求数据
NSString *URLStr = [NSString stringWithFormat:@"www.baidu.com"];
NSURL *url = [NSURL URLWithString:URLStr];
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
[request setTimeoutInterval:20];//设置超时时间
[request setCachePolicy:NSURLRequestReturnCacheDataElseLoad];//设置缓存策略
NSURLSession *session = [NSURLSession sharedSession];
NSURLSessionDataTask *task = [session dataTaskWithRequest:request completionHandler:^(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error) {
if (error == nil) {
dispatch_async(dispatch_get_main_queue(), ^{
NSString *dataStr = [[NSString alloc]initWithData:data encoding:NSUTF8StringEncoding];
NSLog(@"%@",dataStr);
});
}
}];