使用AFN2.0上传图片并且上传进度可见。

用一年多了,一直都是转载和收藏,一直都没有原创,今天下一篇自己的文章。
昨天经理让自己封装一个可看到上传进度的方法,自己就找了找并结合自己的项目搞定了。
先粘代码:

/**
 上传图片,进度可见,
 
 @param dic post请求的body,除图片外其余上传参数;
 @param path 上传路径url;
 @param imagedata 要上传的图片;
 @param success 上传成功回调block;
 @param failure 上传失败回调block;
 @param ProgressBlock 上传进度回调block,第一个参数(totalBytesWritten)已上传字节数,第二个参数(totalBytesExpectedToWrite)要上传的总字节数。
 */
#pragma mark - 上传图片 进度可见
+ (void)uploadFileActionWithBody:(NSDictionary *)dic
                        andPath:(NSString *)path
                       andImage:(UIImage *)imagedata
                        success:(void (^)(id responseObject))success
                        failure:(void (^)(AFHTTPRequestOperation *operation, NSError *error))failure
            UploadProgressBlock:(void (^)(long long totalBytesWritten,
                                          long long totalBytesExpectedToWrite))ProgressBlock
{
    //先判断网络
    Reachability *reach = [Reachability reachabilityForInternetConnection];
    NetworkStatus status = [reach currentReachabilityStatus];
    if (status == NotReachable) {
        [[CommomBlackTips alloc]blackAlert:@"当前网络不可用\n请检查网络设置"];
        return;
    }
    // 0. 将图片压缩
    NSData *imageData = UIImageJPEGRepresentation(imagedata, 1);
    
    // 1. Create `AFHTTPRequestSerializer` which will create your request.
    AFHTTPRequestSerializer *serializer = [AFHTTPRequestSerializer serializer];
    
    // 2. Create an `NSMutableURLRequest`.
    NSMutableURLRequest *request =
    [serializer multipartFormRequestWithMethod:@"POST" URLString:path
                                    parameters:dic
                     constructingBodyWithBlock:^(id formData) {
                         [formData appendPartWithFileData:imageData
                                                     name:@"file"   //这里是图片对应的参数,跟后台商量好
                                                 fileName:@"text.jpg"  //一个图片的时候可以写死,多个图片一起上传不能写死
                                                 mimeType:@"image/jpeg"];
                     }];
    // 3. Create and use `AFHTTPRequestOperationManager` to create an `AFHTTPRequestOperation` from the `NSMutableURLRequest` that we just created.
    AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
    AFHTTPRequestOperation *operation =
    [manager HTTPRequestOperationWithRequest:request
                                     success:^(AFHTTPRequestOperation *operation, id responseObject) {
                                         
                                         success(responseObject);
                                         
                                     } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
                                         
                                         failure(operation, error);
                                         
                                     }];
    // 4. Set the progress block of the operation.
    [operation setUploadProgressBlock:^(NSUInteger __unused bytesWritten,
                                        long long totalBytesWritten,
                                        long long totalBytesExpectedToWrite) {
//        NSLog(@"Wrote %lld/%lld", totalBytesWritten, totalBytesExpectedToWrite);
        //上传进度
        ProgressBlock(totalBytesWritten , totalBytesExpectedToWrite);
        
    }];
    
    // 5. Begin!
    [operation start];
}

其实很简单,AFN内部提供了上传文件时的回调方法,有专门的方法查看已上传部分的大小(字节)。
下面这个方法会一直回调,直到上传成功,也就是totalBytesWritten(已上传部分字节数) 和 totalBytesExpectedToWrite(总字节数)相等之后。

//就是这个方法
setUploadProgressBlock:^(NSUInteger __unused bytesWritten,
                                        long long totalBytesWritten,
                                        long long totalBytesExpectedToWrite) 

下面是我调用的demo:

UITextField *nicheng  = [infomationTableView viewWithTag:1001];
    UITextField *name  = [infomationTableView viewWithTag:1002];
    UITextField *company  =[infomationTableView viewWithTag:1003];
    UITextField *duty  = [infomationTableView viewWithTag:1004];
    UITextField *worktime  = [infomationTableView viewWithTag:1005];
    
    NSString *nickname =[NSString stringWithFormat:@"%@", [NSString stringWithFormat:@"%@" ,nicheng.text]];
    NSString *realname =[NSString stringWithFormat:@"%@", [NSString stringWithFormat:@"%@",name.text]];
    NSString *userbirth =[NSString stringWithFormat:@"%@",[NSString stringWithFormat:@"%@", birthStr]];
    NSString *usercompany =[NSString stringWithFormat:@"%@", [NSString stringWithFormat:@"%@",company.text]];
    NSString *userduty =[NSString stringWithFormat:@"%@", [NSString stringWithFormat:@"%@", duty.text]] ;
    NSString *userworktime = [NSString stringWithFormat:@"%@", [NSString stringWithFormat:@"%@", worktime.text]];
    NSMutableDictionary *params = [[NSMutableDictionary alloc]initWithCapacity:0];
    [params setObject:nickname forKey:@"nickName"];
    [params setObject:realname forKey:@"name"];
    [params setObject:sexStr forKey:@"sex"];
    [params setObject:userbirth forKey:@"birthday"];
    [params setObject:usercompany forKey:@"enterprise"];
    [params setObject:userduty forKey:@"post"];
    [params setObject:userworktime forKey:@"workLife"];
    
    //上面是除了图片外其他参数,比如上传个人资料的时候除了头像还有姓名,学校,身份证号啥的,可有可无(params可为空)。下面是方法调用。
    [RequestRelatedClass uploadFileActionWithBody:params andPath:INTERNET_personalData andImage:headerImage success:^(id responseObject) {
        NSLog(@"上传成功 = %@",responseObject);
    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
        NSLog(@"上传失败 = %@",error.description);
    } UploadProgressBlock:^(long long totalBytesWritten, long long totalBytesExpectedToWrite) {
        NSLog(@"Wrote %lld/%lld", totalBytesWritten, totalBytesExpectedToWrite);
    }];

注释:
1、请求之前判断网络,用到了Reachability这个类,百度可以查到,用的时候#import "Reachability.h"
2、因为我们项目较早,用的是AFN2.0,但是AFN2.0不支持ipv6,建议大家用AFN3.0,其实AFN3.0的上传进度方法更简单;
3、有不足之处请大神指正。

你可能感兴趣的:(使用AFN2.0上传图片并且上传进度可见。)