iOS网络-NSURLSessionUploadTask文件上传

1)实现文件上传的方法

/*
     第一个参数:请求对象
     第二个参数:请求体(要上传的文件数据)跟NSURLConnection文件上传的请求体一样 [self bodyData]放在该方法实现
     第二个参数:当接收到服务器返回数据时调用
         NSData:响应体
         NSURLResponse:响应头
         NSError:请求的错误信息
     */

NSURLSessionUploadTask *uploadTask = [session uploadTaskWithRequest:request fromData:[self bodyData] completionHandler:^(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error) {
        // 里面解析服务器返回的数据
}];

2)设置代理,在代理方法中监听文件上传进度

/*
 调用该方法上传文件数据
 如果文件数据很大,那么该方法会被调用多次
 参数说明:
     totalBytesSent:已经上传的文件数据的大小
     totalBytesExpectedToSend:文件的总大小
 */
-(void)URLSession:(nonnull NSURLSession *)session task:(nonnull NSURLSessionTask *)task didSendBodyData:(int64_t)bytesSent totalBytesSent:(int64_t)totalBytesSent totalBytesExpectedToSend:(int64_t)totalBytesExpectedToSend
{
    NSLog(@"%.2f",1.0 * totalBytesSent/totalBytesExpectedToSend);
}
原文地址:https://www.cnblogs.com/liugengqun/p/5140161.html