iOS网络开发之NSURLSession文件上传、下载(带进度监听)

自iOS9以后,NSURLConnection就被apple给废弃掉了(审核也通不过了),继而有了一个新的API:NSURLSession,这个新的API在文件上传的时候封装了某些代码,相比于NSURLConnection省去了拼接请求体的格式信息,因为那些格式信息是固定的,不能写错一下,而NSURLSession省去了那些拼接代码,而是直接在block里面看上传结果,方便了程序员写代码.并且在下载和上传方面,NSURLSession 支持程序的后台下载和上传, 苹果官方将其称之进程之外的上传和下载, 这些任务都交给后台守护线程完成, 而不是应用本身, 及时文件在下载和上传过程中崩溃了也可以继续运行(如果用户强制关闭程序的话, NSURLSession会断开连接),这里值的注意的是使用NSURLSession构建task的时候,上传可以同时使用代理和block,而下载的时候只能二选其一,废话不多说,上代码:

1.上传

#pragma mark --uploadData
- (void)uploadData {
    /* * 文件上传的时候需要设置请求头中Content-Type类型, 必须使用URL编码,
     application/x-www-form-urlencoded:默认值,发送前对所有发送数据进行url编码,支持浏览器访问,通常文本内容提交常用这种方式。
     multipart/form-data:多部分表单数据,支持浏览器访问,不进行任何编码,通常用于文件传输(此时传递的是二进制数据) 。
     text/plain:普通文本数据类型,支持浏览器访问,发送前其中的空格替换为“+”,但是不对特殊字符编码。
     application/json:json数据类型,浏览器访问不支持 。
     text/xml:xml数据类型,浏览器访问不支持。
     multipart/form-data 必须进行设置,
     */
    // 1. 创建UR
    NSURL *url = [NSURL URLWithString:[@"" stringByAddingPercentEncodingWithAllowedCharacters:[NSCharacterSet URLQueryAllowedCharacterSet]]];
    // 2. 创建请求
    NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
    // 设置请求的为POST
    request.HTTPMethod = @"POST";
    //3.设置request的body
    request.HTTPBody = _uploadData;
    // 设置请求头 Content-Length
    [request setValue:[NSString stringWithFormat:@"%lu", (unsigned long)_uploadData.length] forHTTPHeaderField:@"Content-Length"];
    // 设置请求头 Content-Type
    [request setValue:[NSString stringWithFormat:@"multipart/form-data; boundary=%@",kBoundary] forHTTPHeaderField:@"Content-Type"];
    // 4. 创建会话
    NSURLSession *session = [NSURLSession sharedSession];
    NSURLSessionUploadTask *uploadTask = [session uploadTaskWithRequest:request fromData:_uploadData completionHandler:^(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error) {
        if (!error) {
            // 上传成功
        }else {
            // 上传失败, 打印error信息
            NSLog(@"error --- %@", error.localizedDescription);
        }
    }];
    // 恢复线程 启动任务
    [uploadTask resume];
}

//使用NSURLSessionTaskDelegate代理监听上传进度
#pragma mark --NSURLSessionTaskDelegate
- (void)URLSession:(NSURLSession *)session task:(NSURLSessionTask *)task
   didSendBodyData:(int64_t)bytesSent
    totalBytesSent:(int64_t)totalBytesSent
totalBytesExpectedToSend:(int64_t)totalBytesExpectedToSend {
    // 计算进度
    float progress = (float)totalBytesSent / totalBytesExpectedToSend;
    NSLog(@"进度 %f",progress);
}

2.下载

#pragma mark --downLoad
- (void)download {
    //默认配置
    NSURLSessionConfiguration *config = [NSURLSessionConfiguration defaultSessionConfiguration];
    //会话
    _downLoadSession = [NSURLSession sessionWithConfiguration:config delegate:self delegateQueue:[NSOperationQueue mainQueue]];
    //构建request
    NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:@"http://download.xmcdn.com/group18/M01/BC/91/wKgJKlfAEN6wZgwhANQvLrUQ3Pg146.aac"]];
    _downLoadTask = [_downLoadSession downloadTaskWithRequest:request];
    //不带进度
    _downLoadTask = [_downLoadSession downloadTaskWithRequest:request
                                            completionHandler:^(NSURL * _Nullable location, NSURLResponse * _Nullable response, NSError * _Nullable error) {
                                                //下载完成之后的回调
                                            }];
    //手动开启
    [_downLoadTask resume];
}

- (void)pauseDownload {
    //取消下载
    [_downLoadTask  cancelByProducingResumeData:^(NSData * _Nullable resumeData) {
        _downLoadData = [NSMutableData dataWithData:resumeData];
    }];
    _downLoadTask = nil;
}

- (void)resumDownload {
    //恢复下载
    _downLoadTask = [_downLoadSession  downloadTaskWithResumeData:_downLoadData];
    [_downLoadTask resume];
}

- (void)suspendDownLoad {
    [_downLoadTask suspend];
}

#pragma mark --NSURLSessionDownloadDelegate
- (void)URLSession:(NSURLSession *)session downloadTask:(NSURLSessionDownloadTask *)downloadTask
didFinishDownloadingToURL:(NSURL *)location {
    //写入沙盒文件
    NSString *documentPath = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) firstObject];
    NSString *downLoadPath = [documentPath stringByAppendingPathComponent: downloadTask.response. suggestedFilename];
    [[NSFileManager defaultManager] moveItemAtPath:location.path toPath:downLoadPath error:nil];
    NSLog(@"downLoad = %@",location.path);
}

- (void)URLSession:(NSURLSession *)session downloadTask:(NSURLSessionDownloadTask *)downloadTask
      didWriteData:(int64_t)bytesWritten
 totalBytesWritten:(int64_t)totalBytesWritten
totalBytesExpectedToWrite:(int64_t)totalBytesExpectedToWrite {
    //进度百分比
    NSString *subStr = @"%";
    NSLog(@"percent =%@%.2f",subStr,100.0 *totalBytesWritten / totalBytesExpectedToWrite);
}

-(void)URLSession:(NSURLSession *)session task: (NSURLSessionTask *)task didCompleteWithError:(NSError *)error {
    NSLog(@" function == %s, line == %d, error ==  %@",__FUNCTION__,__LINE__,error);
}
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容