1主要包含三个请求方法:NSURLSessionDataTask,NSURLSessionDownloadTask,NSURLSessionUploadTask。
2.第一种请求方法 --GET
-(void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event{
NSURL *url = [NSURLURLWithString:@"http://img03.tooopen.com/images/20160630/tooopen_sy_168334097794.jpg"];
NSURLRequest *request = [NSURLRequestrequestWithURL:url];
NSURLSession *session = [NSURLSessionsharedSession];
NSURLSessionDataTask *task = [session dataTaskWithRequest:request
completionHandler:^(NSData *_Nullable data, NSURLResponse *_Nullable response, NSError * _Nullable error) {
[selfshowImage:data];
NSLog(@"%@",data);
}];
[task resume];
}
-(void)showImage:(NSData *)data{
_imageView = [[UIImageViewalloc]initWithFrame:CGRectMake(10,5, 100,100)];
_imageView.image = [UIImageimageWithData:data];
[self.viewaddSubview:_imageView];
}
3.第二种请求方法,如果要设置请求头就得创建Request。---GET
NSURLSession *session = [NSURLSessionsharedSession];
NSURLSessionDataTask *dataTask = [sessiondataTaskWithURL:[NSURLURLWithString:@"http://img03.tooopen.com/images/20160630/tooopen_sy_168334097794.jpg" ]completionHandler:^(NSData *_Nullable data, NSURLResponse *_Nullable response, NSError * _Nullable error) {
[self showImage:data];
}];
[dataTask resume];
4.第三种请求方法 -- POST
NSURL *url = [NSURLURLWithString:@"http://img03.tooopen.com/images/20160630/tooopen_sy_168334097794.jpg"];
NSURLSession *session = [NSURLSessionsharedSession];
NSMutableURLRequest *request = [NSURLRequestrequestWithURL:url];
request.HTTPMethod = @"POST";
request.HTTPBody = [@"username=123&ped=123"dataUsingEncoding:NSUTF8StringEncoding];
NSURLSessionDataTask *dataTask = [sessiondataTaskWithRequest:request completionHandler:^(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error) {
NSLog(@"%@",data);
}];
[dataTask resume];
5.文件下载:默认存储在temp,需要手动存储在沙盒
NSURL *url = [NSURLURLWithString:@"http://img03.tooopen.com/images/20160630/tooopen_sy_168334097794.jpg"];
NSURLSession *session = [NSURLSessionsharedSession];
NSURLSessionDownloadTask *sessionTask = [sessiondownloadTaskWithURL:url completionHandler:^(NSURL * _Nullable location, NSURLResponse * _Nullable response, NSError * _Nullable error) {
NSLog(@"-------ok!");
//剪切location的临时文件到真实位置
NSString *file = [[NSSearchPathForDirectoriesInDomains(NSCachesDirectory,NSUserDomainMask, YES)lastObject]stringByAppendingPathComponent:response.suggestedFilename];
NSFileManager *mgr = [NSFileManagerdefaultManager];
[mgr moveItemAtURL:location toURL:[NSURL fileURLWithPath:file] error:
nil];
}];
[sessionTask resume];
6.代理NSURLSessionDelegate
-(void)download1{
NSURLSession *session = [NSURLSessionsessionWithConfiguration:[NSURLSessionConfigurationdefaultSessionConfiguration] delegate:selfdelegateQueue:[[NSOperationQueuealloc]init]];
NSURLSessionDataTask *task = [sessiondataTaskWithRequest:[NSURLRequestrequestWithURL:[NSURLURLWithString:@""]]];
[task resume];
[task cancel];
[task suspend];
}
//接受到服务器的数据,可能会被多次调用。
-(void)URLSession:(NSURLSession *)session dataTask:(nonnullNSURLSessionDataTask *)dataTask didReceiveData:(nonnullNSData *)data{
}
//接收服务器的响应
-(void)URLSession:(NSURLSession *)session dataTask:(nonnullNSURLSessionDataTask *)dataTask didReceiveResponse:(nonnullNSURLResponse *)response completionHandler:(nonnullvoid (^)(NSURLSessionResponseDisposition))completionHandler{
//允许服务器的响应,才会继续接受服务器返回
completionHandler(NSURLSessionResponseAllow);
/**
* 补充NSUrlSessionTask创建的任务
*
* Task可以暂停盒挂起。
*/
}
//请求完毕,成功/失败。
-(void)URLSession:(NSURLSession *)session task:(nonnullNSURLSessionTask *)task didCompleteWithError:(nullableNSError *)error{
}
7.注意点,只要是NSURLSessionTask创建的任务Task,就可以:
-(void)suspend;//暂停
-(void)cancel;//取消
-(void)resume;//恢复
@property(readonly,copy)NSError *error;//错误
@property(readonly,copy)NSURLResponse *response;//响应
8.大文件下载
-(void)downLoadBigFile{
NSURLSession *session = [NSURLSessionsessionWithConfiguration:[NSURLSessionConfigurationdefaultSessionConfiguration] delegate:selfdelegateQueue:[[NSOperationQueuealloc]init]];
NSURLSessionDownloadTask *downloadTask = [sessiondownloadTaskWithURL:[NSURLURLWithString:@""]];
[downloadTask resume];
}
-(void)URLSession:(NSURLSession *)session downloadTask:(NSURLSessionDownloadTask *)downloadTask didResumeAtOffset:(int64_t)fileOffset expectedTotalBytes:(int64_t)expectedTotalBytes{
}
//每当写入临时文件时就会调用
/**
* <#Description#>
*
* @param session <#session description#>
* @param downloadTask <#downloadTask description#>
* @param bytesWritten 这次写入
* @param totalBytesWritten 文件已写入
* @param totalBytesExpectedToWrite 文件总大小
*/
-(void)URLSession:(NSURLSession *)session downloadTask:(NSURLSessionDownloadTask *)downloadTask didWriteData:(int64_t)bytesWritten totalBytesWritten:(int64_t)totalBytesWritten totalBytesExpectedToWrite:(int64_t)totalBytesExpectedToWrite{
float progress = 1 * totalBytesWritten / totalBytesExpectedToWrite;
}
//下载完毕就会调用这个方法。
-(void)URLSession:(NSURLSession *)session downloadTask:(NSURLSessionDownloadTask *)downloadTask didFinishDownloadingToURL:(NSURL *)location{
NSString *file = [[NSSearchPathForDirectoriesInDomains(NSCachesDirectory,NSUserDomainMask, YES)lastObject]stringByAppendingPathComponent:downloadTask.response.suggestedFilename];
NSFileManager *mgr = [NSFileManagerdefaultManager];
[mgr moveItemAtURL:locationtoURL:[NSURLfileURLWithPath:file] error:nil];
}
-(void)URLSession:(NSURLSession *)session task:(NSURLSessionTask *)task didCompleteWithError:(NSError *)error{
}
9.断电下载:思路
-(NSURLSession *)session{
if (_session ==nil) {
_session = [NSURLSessionsessionWithConfiguration:[NSURLSessionConfigurationdefaultSessionConfiguration] delegate:selfdelegateQueue:[[NSOperationQueuealloc]init]];
}
return _session;
}
#define WCY [[NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES)lastObject]stringByAppendingPathComponent:@"resumeData.temp" ]
-(NSData *)resumeData{
if (_resumeData ==nil) {
_resumeData = [NSDatadataWithContentsOfFile:WCY];
}
return_resumeData;
}
- (IBAction)Start:(id)sender {
if (self.resumeData) {
self.downloadTask = [_sessiondownloadTaskWithResumeData:self.resumeData];
}else{
_downloadTask = [_sessiondownloadTaskWithURL:[NSURLURLWithString:@""]];
}
[_downloadTaskresume];
}
- (IBAction)Pause:(id)sender {
// [_downloadTask suspend];
[_downloadTask cancelByProducingResumeData:^(NSData * _Nullable resumeData) {
/**
* rsumrData:记录上次下载的信息。
*/
self.resumeData = resumeData;
// 可以将上一次保存的数据写入沙盒保存。
[resumeData writeToFile:WCYatomically:YES];
// 缓存空间
NSString *tmp = NSTemporaryDirectory();
}];
}
- (IBAction)GoOn:(id)sender {
self.downloadTask = [self.sessiondownloadTaskWithResumeData:self.resumeData];
[_downloadTask resume];
}
-(void)URLSession:(NSURLSession *)session downloadTask:(NSURLSessionDownloadTask *)downloadTask didResumeAtOffset:(int64_t)fileOffset expectedTotalBytes:(int64_t)expectedTotalBytes{
}
//每当写入临时文件时就会调用
/**
* <#Description#>
*
* @param session <#session description#>
* @param downloadTask <#downloadTask description#>
* @param bytesWritten 这次写入
* @param totalBytesWritten 文件已写入
* @param totalBytesExpectedToWrite 文件总大小
*/
-(void)URLSession:(NSURLSession *)session downloadTask:(NSURLSessionDownloadTask *)downloadTask didWriteData:(int64_t)bytesWritten totalBytesWritten:(int64_t)totalBytesWritten totalBytesExpectedToWrite:(int64_t)totalBytesExpectedToWrite{
float progress = 1 * totalBytesWritten / totalBytesExpectedToWrite;
}
//下载完毕就会调用这个方法。
-(void)URLSession:(NSURLSession *)session downloadTask:(NSURLSessionDownloadTask *)downloadTask didFinishDownloadingToURL:(NSURL *)location{
NSString *file = [[NSSearchPathForDirectoriesInDomains(NSCachesDirectory,NSUserDomainMask, YES)lastObject]stringByAppendingPathComponent:downloadTask.response.suggestedFilename];
NSFileManager *mgr = [NSFileManagerdefaultManager];
[mgr moveItemAtURL:locationtoURL:[NSURLfileURLWithPath:file] error:nil];
}
-(void)URLSession:(NSURLSession *)session task:(NSURLSessionTask *)task didCompleteWithError:(NSError *)error{
}
[[NSMutableURLRequest requestWithURL:[NSURL URLWithString:@"www"]]setValue:@"10234" forHTTPHeaderField:@"Range"];
11.如果非正常下载失败,在下面的方法中保存数据。
-(void)URLSession:(NSURLSession *)session task:(NSURLSessionTask *)task didCompleteWithError:(NSError *)error{
// 如果因为其他原因失败,保存resumeData
self.resumeData = error.userInfo[NSURLSessionDownloadTaskResumeData];
}
- (NSURLSession *)session
{
if (!_session) {
NSURLSessionConfiguration *cfg = [NSURLSessionConfiguration defaultSessionConfiguration];
cfg.timeoutIntervalForRequest = 10;
// 是否允许使用蜂窝网络(手机自带网络)
cfg.allowsCellularAccess = YES;
_session = [NSURLSession sessionWithConfiguration:cfg];
}
return _session;
}
- (void)viewDidLoad {
[super viewDidLoad];
}
- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event {
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:@"http://120.25.226.186:32812/upload"]];
request.HTTPMethod = @"POST";
// 设置请求头(告诉服务器,这是一个文件上传的请求)
[request setValue:[NSString stringWithFormat:@"multipart/form-data; boundary=%@", WCYBoundary] forHTTPHeaderField:@"Content-Type"];
// 设置请求体
NSMutableData *body = [NSMutableData data];
// 文件参数
// 分割线
[body appendData:WCYEncode(@"--")];
[body appendData:WCYEncode(WCYBoundary)];
[body appendData:WCYNewLine];
// 文件参数名
[body appendData:WCYEncode([NSString stringWithFormat:@"Content-Disposition: form-data; name=\"file\"; filename=\"test.png\""])];
[body appendData:WCYNewLine];
// 文件的类型
[body appendData:WCYEncode([NSString stringWithFormat:@"Content-Type: image/png"])];
[body appendData:WCYNewLine];
// 文件数据
[body appendData:WCYNewLine];
[body appendData:[NSData dataWithContentsOfFile:@"/Users/Desktop/test.png"]];
[body appendData:WCYNewLine];
// 结束标记
/*
--分割线--\r\n
*/
[body appendData:WCYEncode(@"--")];
[body appendData:WCYEncode(WCYBoundary)];
[body appendData:WCYEncode(@"--")];
[body appendData:WCYNewLine];
[[self.session uploadTaskWithRequest:request fromData:body completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) {
NSLog(@"-------%@", [NSJSONSerialization JSONObjectWithData:data options:kNilOptions error:nil]);
}] resume];
}