美文网首页
NSURLSession 上传图片带进度

NSURLSession 上传图片带进度

作者: 白色天空729 | 来源:发表于2019-12-09 17:02 被阅读0次
 //分隔符
#define YFBoundary @"AnHuiWuHuYungFan"
//换行
#define YFEnter [@"\r\n" dataUsingEncoding:NSUTF8StringEncoding]
//NSString转NSData
#define YFEncode(string) [string dataUsingEncoding:NSUTF8StringEncoding]
typedef void (^XTOriginResultBlock)(NSInteger status, id _Nullable result);

#pragma mark --uploadData
- (void)netWorkUrlUserPost:(NSString *)url UploadImage:(UIImage *)image FileName:(NSString *)fileName Block:(XTOriginResultBlock)block {
   //1、确定URL
   NSURL *url2 = [NSURL URLWithString:url];
   //2、确定请求
   NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url2];
   //3、设置请求头
   NSString *head = [NSString stringWithFormat:@"multipart/form-data;boundary=%--@", YFBoundary];
   [request setValue:head forHTTPHeaderField:@"Content-Type"];
   //4、设置请求方式,上传时必须是Post请求
   request.HTTPMethod = @"POST";
   //5、创建NSURLSession
   NSURLSession *session = [NSURLSession sessionWithConfiguration:[NSURLSessionConfiguration defaultSessionConfiguration] delegate:self delegateQueue:[NSOperationQueue mainQueue]];
   //6、获取上传的数据
    NSData *uploadData = [self getData:image withFileName:fileName];
   //7、创建上传任务 上传的数据来自getData方法
   NSURLSessionUploadTask *task = [session uploadTaskWithRequest:request fromData:uploadData completionHandler:^(NSData *responseObject, NSURLResponse *response, NSError *error) {
       NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:responseObject options:NSJSONReadingMutableContainers error:nil];

       if (dic == nil) {
           NSDictionary *errorInfo = @{
                                       @"status" : @(200),
                                       @"url" : url,
                                       @"data" : @{},
                                       @"headers" : @{}
                                       };
           block(1,errorInfo);

       } else {
           block(0,dic);
       }
       
       if (error) {
           block(-1,[error userInfo].description);
           [self notifiTologin:error];
       }
       
       [SVProgressHUD dismiss];
   }];
   //8、执行上传任务
   [task resume];
}


/**
 *  设置请求体
 *
 *  @return 请求体内容
 */
-(NSData *)getData:(UIImage *)withImage withFileName:(NSString *)fileName {
    
    DEBUGLOG(@"%@",fileName);
    
    NSMutableData *data = [NSMutableData data];

    //1、开始标记
    //--
    [data appendData:YFEncode(@"--")];
    //boundary
    [data appendData:YFEncode(YFBoundary)];
    //换行符
    [data appendData:YFEnter];
    //文件参数名 Content-Disposition: form-data; name="myfile"; filename="wall.jpg"
    
    NSString *uploadFileName = [[@"Content-Disposition:form-data; name=\"myfile\"; filename=\"" stringByAppendingString:fileName] stringByAppendingString:@"\""];
    [data appendData:YFEncode(uploadFileName)];
    //换行符
    [data appendData:YFEnter];
    //Content-Type 上传文件的类型 MIME
    [data appendData:YFEncode(@"Content-Type:image/jpeg")];
    //换行符
    [data appendData:YFEnter];
    //换行符
    [data appendData:YFEnter];
    //2、上传的文件数据

    //图片数据  并且转换为Data
    UIImage *image = withImage;
    NSData *imagedata = UIImageJPEGRepresentation(image, 1.0);
    [data appendData:imagedata];
    //换行符
    [data appendData:YFEnter];

    //3、结束标记
    //--
    [data appendData:YFEncode(@"--")];
    //boundary
    [data appendData:YFEncode(YFBoundary)];
    //--
    [data appendData:YFEncode(@"--")];
    //换行符
    [data appendData:YFEnter];
    return data;
}


//使用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;
    DEBUGLOG(@"进度 %f",progress);
    
    [SVProgressHUD showProgress:progress status:@"文件上传中,请稍后"];
}

思路参考:https://www.jianshu.com/p/399e66d39d56

相关文章

网友评论

      本文标题:NSURLSession 上传图片带进度

      本文链接:https://www.haomeiwen.com/subject/glqigctx.html