NSURLSession下载上传

最近呢由于自己工作需要封装一个使用NSURLSession上传下载的类,于是在封装完毕之后对NSURLSession有了一点的了解,这篇主要以代码为主,demo已经上传至git,地址会在下方给大家,希望喜欢的可以点个赞。

NSURLSession

NSURLSession是iOS7中新的网络接口,与NSURLConnection并列,但是NSURLConnection在iOS9以后已经被弃用了,现在最新的AF底层也是使用的NSURLSession来进行封装,在2013年被苹果提出并继任NSURLConnection。
NSURLSession具有一些新的特性,

  • 它可以支持后台相关的网络操作,支持后台的下载和上传
  • 下载的数据可以直接放到磁盘
  • 同一个session可以发送多个请求,只用建立一次连接
  • 提供了一个全局的session来配置,使用方便
  • 下载使用的多线程异步处理,更加高效

NSURLSession的使用步骤

  • 通过NSURLSession实例创建task
  • 执行task

NSURLSessionTask

NSURLSessionTask有三个子类:

  • NSURLSessionDataTask:获取数据
  • NSURLSessionUploadTask:上传文件
  • NSURLSessionDownloadTask:下载文件

获取数据

先说一下获取数据吧,主要是两类,一个GET请求获取数据,另一个POST请求获取数据。

GET请求

// 快捷方式获得session对象
NSURLSession *session = [NSURLSession sharedSession];
//获取数据地址
NSString *questStr = @"";
 NSURL *url = [NSURL URLWithString:[NSString stringWithFormat:@"%@",questStr]];
// 通过URL初始化task,在block内部可以直接对返回的数据进行处理
NSURLSessionTask *task = [session dataTaskWithURL:url completionHandler:^(NSData *data, NSURLResponse *response, NSError* error) {
        NSLog(@"%@", [NSJSONSerialization JSONObjectWithData:data options:kNilOptions error:nil]);
    }];
// 启动任务
[task resume];

POST请求

//请求地址
NSString *questStr = @"";
NSURL *url = [NSURL URLWithString:[NSString stringWithFormat:@"%@",questStr]];
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
request.HTTPMethod = @"POST";
request.HTTPBody = [@"username=daka&pwd=123" dataUsingEncoding:NSUTF8StringEncoding];
NSURLSession *session = [NSURLSession sharedSession];
// 由于要先对request先行处理,我们通过request初始化task
NSURLSessionTask *task = [session dataTaskWithRequest:request
                                   completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) { NSLog(@"%@", [NSJSONSerialization JSONObjectWithData:data options:kNilOptions error:nil]); }];
[task resume];

使用代理方法请求

NSURL *url = [NSURL URLWithString:[NSString stringWithFormat:@"%@",self.url]];    
 NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url cachePolicy:1 timeoutInterval:[self.timeout integerValue]];    
request.HTTPMethod = @"POST";
NSString *str = [NSString stringWithFormat:@"%@",self.urlPost];    
NSData *data = [str dataUsingEncoding:NSUTF8StringEncoding];
request.HTTPBody = data;    
NSURLSession *session = [NSURLSession sessionWithConfiguration:[NSURLSessionConfiguration defaultSessionConfiguration] delegate:self delegateQueue:[NSOperationQueue mainQueue]];
NSURLSessionDataTask *task = [session dataTaskWithRequest:request];
[task resume];
代理方法
-(void)URLSession:(NSURLSession *)session dataTask:(NSURLSessionDataTask *)dataTask didReceiveResponse:(NSURLResponse *)response completionHandler:(void (^)(NSURLSessionResponseDisposition))completionHandler {
// 允许处理服务器的响应,才会继续接收服务器返回的数据
completionHandler(NSURLSessionResponseAllow);
}
-(void)URLSession:(NSURLSession *)session dataTask:(NSURLSessionDataTask *)dataTask didReceiveData:(NSData *)data {
//处理每次接收的数据
}
-(void)URLSession:(NSURLSession *)session task:(NSURLSessionTask *)task didCompleteWithError:(NSError *)error {
//请求完成,成功或者失败的处理
}

以上三个代理方法是最基本的session的代理方法,有一点需要注意的是,如果创建session时使用的delegateQueue不是主线程的话,在返回数据进行操作时,它开的是一条分线程,对于返回数据以后的操作会有一定的延时,如果开一条线程进行请求操作的话,返回数据需要调用一下主线程来进行操作。

下载

直接上代码:

NSString *imgStr = @"http://a3.topitme.com/f/74/9f/11281073948639f74fo.jpg";
    NSURL *imgUrl = [NSURL URLWithString:imgStr];
    
    NSURLSession *ImgSession = [NSURLSession sharedSession];
    
    NSURLSessionDownloadTask *ImgDownTask = [ImgSession downloadTaskWithURL:imgUrl completionHandler:^(NSURL * _Nullable location, NSURLResponse * _Nullable response, NSError * _Nullable error) {
       //下载到沙盒的地址
        NSLog(@"%@=",location);
        
        //response.suggestedFilename 响应信息中的资源文件名
        NSString *cachePath = [[NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES) lastObject] stringByAppendingPathComponent:response.suggestedFilename];
        
        NSLog(@"缓存地址%@----------------%@",cachePath,DateTime);
        
        //获取文件管理器
        NSFileManager *fileManager = [NSFileManager defaultManager];
        
        //将临时文件移到缓存目录下
        //[NSURL fileURLWithPath:cachesPath] 将本地路径转化为URL类型
        //URL如果地址不正确,生成的url对象为空
        [fileManager moveItemAtURL:location toURL:[NSURL fileURLWithPath:cachePath] error:NULL];
        
        UIImage *image = [UIImage imageWithContentsOfFile:cachePath];
        
        //更新UI需要调取主线程,否则在分线程中执行,图片加载会很慢
        dispatch_async(dispatch_get_main_queue(), ^{
            imageView.image = image;
        });
    }];
    
    [ImgDownTask resume];

下载的文件是直接下载至沙盒中,同样的如果要在下载完成后要进行UI的更新操作需要重新调取一下主线程
上面是一个图片的下载,那么对于大文件的下载如何操作呢,这里需要用到断点续传,对于大文件,自然是不能等到其下载完才可进行操作,所以这时候就需要使用到断点续传,对于大文件的下载来说,流程和普通下载是一样的,都是先行建立一个downloadTask,在执行task,先上代码:

_resumeSession = [NSURLSession sessionWithConfiguration:[NSURLSessionConfiguration defaultSessionConfiguration] delegate:self delegateQueue:[NSOperationQueue mainQueue]];
 _resumeTask = [_resumeSession downloadTaskWithURL:[NSURL URLWithString:@"https://moa.ch999.com/office/file/2b7d301dfc75be810fb5dda9f6920726d41d8cd98f00b204e9800998ecf8427e.mp4"]];    
[_resumeTask resume];

这里会用到下载时使用的代理方法:

/*
 监测临时文件下载的数据大小,当每次写入临时文件时,就会调用一次
 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 * 100);              
}

这个代理方法可以实时监控当前下载进度,从而获取一个下载的百分比

//下载完成
-(void)URLSession:(NSURLSession *)session downloadTask:(NSURLSessionDownloadTask *)downloadTask didFinishDownloadingToURL:(NSURL *)location{
    NSString *catchPath = [[NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES) lastObject] stringByAppendingPathComponent:downloadTask.response.suggestedFilename];
    
    NSFileManager *fileManager = [NSFileManager defaultManager];
    
    [fileManager moveItemAtURL:location toURL:[NSURL fileURLWithPath:catchPath] error:NULL];
    
    //获取本地视频元素
    AVPlayerItem *playerItem = [AVPlayerItem playerItemWithURL:[NSURL fileURLWithPath:catchPath]];
    //创建视频播放器
    _player = [AVPlayer playerWithPlayerItem:playerItem];
    //创建视屏显示的图层
    AVPlayerLayer *showLayer = [AVPlayerLayer playerLayerWithPlayer:_player];
    showLayer.frame = CGRectMake((AllScreen.width - (AllScreen.height - 200) / AllScreen.height * AllScreen.width) / 2, 20, (AllScreen.height - 200) / AllScreen.height * AllScreen.width, (AllScreen.height - 200) / AllScreen.height *AllScreen.height);
    [self.view.layer addSublayer:showLayer];
    //播放视频
    [_player play];
}

这个demo下载的是一个大约90M的小视频,下载完成后可以在这里进行操作,调取视频播放器播放

重点来了

断点续传要做的就是一个暂停和继续的操作
一共只需两行代码:

  • 暂停
//将任务挂起
    [_resumeTask cancelByProducingResumeData:^(NSData * _Nullable resumeData) {
       //将已下载的数据进行保存
        _resumeData = resumeData;
    }];
  • 继续
//使用rusumeData创建任务
    _resumeTask = [_resumeSession downloadTaskWithResumeData:_resumeData]; 
    [_resumeTask resume];

是不是很简单,只需将已经下载好的任务使用一个data来进行存储,当需要进行继续下载操作时,再调用session来建立一个task继续执行就可。

上传

二话不说,直接上代码:

NSURL *uploadUrl = [NSURL URLWithString:[NSString stringWithFormat:@"http://m.9ji.com/app/3_0/UserHandler.ashx?act=UploadImage"]];
    
    NSMutableURLRequest *uploadRequest = [NSMutableURLRequest requestWithURL:uploadUrl];
    
    uploadRequest.HTTPMethod = @"POST";
    
    NSString *contentType = [NSString stringWithFormat:@"multipart/form-data; boundary=%@",@"boundary"];
    
    [uploadRequest setValue:contentType forHTTPHeaderField:@"Content-Type"];
    
    UIImage *image = [UIImage imageNamed:@"图片1.jpg"];
    UIImage *image2 = [UIImage imageNamed:@"图片2.jpg"];
    
    NSMutableArray *imaArr = [[NSMutableArray alloc]init];
    [imaArr addObject:image];
    [imaArr addObject:image2];
    
    uploadRequest.HTTPBody = [self getDataBodyWithImgArr:imaArr];
    
    [[[NSURLSession sharedSession] dataTaskWithRequest:uploadRequest completionHandler:^(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error) {
        if (error == nil) {
            UILabel *textLbl = (id)[self.view viewWithTag:4000];
            NSLog(@"upload success:%@",[[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding]);
            dispatch_async(dispatch_get_main_queue(), ^{
                textLbl.text = [NSString stringWithFormat:@"%@",[[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding]];
            });
        } else {
            NSLog(@"upload error:%@",error);
        }
        
    }] resume];

这块代码和上面的是不是差不多?这个不是重点,重点在下面:

-(NSData *)getDataBodyWithImgArr:(NSArray *)imgArr{
    //每个文件上传须遵守W3C规则进行表单拼接
    NSMutableData * data=[NSMutableData data];
    
    for (int i = 0; i < 2; i++) {
        NSMutableString *headerStrM =[NSMutableString string];
        [headerStrM appendFormat:@"\r\n--%@\r\n",@"boundary"];
        [headerStrM appendFormat:@"Content-Disposition: form-data; name=\"file%d\"; filename=\"filename%d\"\r\n",i,i];
        [headerStrM appendFormat:@"Content-Type: application/octet-stream\r\n\r\n"];
        [data appendData:[headerStrM dataUsingEncoding:NSUTF8StringEncoding]];
        NSData *imgData = UIImageJPEGRepresentation(imgArr[i], 0.5);
        [data appendData:imgData];
    }
    
    NSMutableString *footerStrM = [NSMutableString stringWithFormat:@"\r\n--%@--\r\n",@"boundary"];
    [data appendData:[footerStrM  dataUsingEncoding:NSUTF8StringEncoding]];
    
    return data;
}

没错,这里就是重点,不管对于单个文件上传还是多文件上传,都需要进行一个表单拼接,那么表单怎么拼接呢,它需要一个存储在服务器上的名称,也就是文件名,这个可以没有,需要上传文件的类型,这个是必须有的,尤其对于视频语音的上传。它有一个拼接的规则:

  • 单个文件:
    第一部分:请求头
    第二部分:请求体(包括文件的表单头和尾)
    第三部分:请求尾
  • 多个文件
    第一部分:请求头
    第一个文件:文件表单头,文件本身data
    第二个文件:文件表单头,文件本身data
    第三部分:请求尾
    就是这么一个格式就可以上传成功

注意:

在拼接表单体的时候,一定要注意换行符的拼接,因为少了一个换行符,就会导致识别不出,虽然传了几个文件上去,但是只能识别出第一个,这次项目中我就被这个拼接弄出了一个深坑。
好了,这里贴出项目地址:https://github.com/Archerry/NSURLSession
该项目我写完之后第一次运行可能会有一次崩溃,由于现在不太方便,目测是开启用户数据请求权限的原因,如有遇到,可以多运行两次,图片链接和视频链接大家可以换成自己喜欢的放上去试试看。
这些就是NSURLSession的一些基本用法,对于表单拼接,暂时还不是太过熟悉,只知道要遵循一个W3C的标准,希望了解的大侠可以在下方丢个链接或者略作指点,欢迎大家拍砖交流,也可以顺手点一下喜欢。

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