AFNetworking3.0 post请求,纯代码,拿去不谢

96
Die丶别离
2016.06.02 17:52* 字数 21
#import <Foundation/Foundation.h>

@interface AFNetworkTool : NSObject

+(AFNetworkTool *)sharedManager;

/**
 *  发送一个POST请求
 *
 *  @param url     请求路径
 *  @param params  请求参数
 *  @param formdata追加数据的回调  (请将追加的其他格式数据写到这个block中)
 *  @param progress请求进程的回调  (请将进程的事情写到这个block中)
 *  @param success 请求成功后的回调(请将请求成功后想做的事情写到这个block中)
 *  @param failure 请求失败后的回调(请将请求失败后想做的事情写到这个block中)
 */
- (void)HTTPPost:(NSString *)url parameters:(NSDictionary *)parameters formdata:(void(^)(id<AFMultipartFormData>formdata))formdata  progress:(void(^)(NSProgress *uploadProgress))progress success:(void (^)(id responseObj))success failure:(void (^)(NSError *error))failure;


@end
#import "AFNetworkTool.h"

@implementation AFNetworkTool

#pragma mark --  使用单例、GCD一次创建
+(AFNetworkTool *)sharedManager
{
    static AFNetworkTool *af=nil;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        af=[[AFNetworkTool alloc]init];
    });
    return af;
}

#pragma mark -- post请求
- (void)HTTPPost:(NSString *)url parameters:(NSDictionary *)parameters formdata:(void (^)(id<AFMultipartFormData>))formdata progress:(void (^)(NSProgress *))progress success:(void (^)(id))success failure:(void (^)(NSError *))failure{
    // 开启网络指示器
    [[UIApplication sharedApplication] setNetworkActivityIndicatorVisible:YES];
    
    AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
    manager.requestSerializer = [AFHTTPRequestSerializer serializer];
    manager.responseSerializer = [AFHTTPResponseSerializer serializer];
    // 设置超时时间
    [manager.requestSerializer willChangeValueForKey:@"timeoutInterval"];
    manager.requestSerializer.timeoutInterval = 20.f;
    [manager.requestSerializer didChangeValueForKey:@"timeoutInterval"];
    
    /*
     *从本地获取请求头参数
     **/
    // token
    NSString *token = [[NSUserDefaults standardUserDefaults]objectForKey:@"token"];
    // requestkey
    //获取系统当前的时间戳
    NSDate* dat = [NSDate dateWithTimeIntervalSinceNow:0];
    NSTimeInterval a=[dat timeIntervalSince1970]*1000;
    NSString *timeString = [MSEncryptUtil encryptUseDES:[NSString stringWithFormat:@"%f", a] key:token];//转为字符型
    
    // 截取token
    NSRange rangeleft = NSMakeRange(0, 4);
    NSString *tokenleft = [token substringWithRange:rangeleft];
    
    NSRange rangeright = NSMakeRange(4, 4);
    NSString *tokenright = [token substringWithRange:rangeright];
    
    
    NSString *requestkey = [NSString stringWithFormat:@"%@%@%@",tokenleft,timeString,tokenright];
    
    //orgcode
    NSString *orgcodeOne = [[NSUserDefaults standardUserDefaults]objectForKey:@"organization"];
    NSString *orgcode = [MSEncryptUtil encryptUseDES:[NSString stringWithFormat:@"%@", orgcodeOne] key:token];
    
    // 设置请求头参数
    // token
    [manager.requestSerializer setValue:token forHTTPHeaderField:@"token"];
    //requestkey
    [manager.requestSerializer setValue:requestkey forHTTPHeaderField:@"requestkey"];
    //经销商代码
    [manager.requestSerializer setValue:orgcode forHTTPHeaderField:@"orgcode"];
    
    // 请求参数类型
    manager.responseSerializer.acceptableContentTypes = [NSSet setWithObjects:@"application/json",@"text/json",@"text/xml",@"text/html", nil ];
    // post请求
    [manager POST:url parameters:parameters constructingBodyWithBlock:^(id<AFMultipartFormData>  _Nonnull formData) {
        
        if (formdata)
        {
            formdata(formData);
        }
        
    } progress:^(NSProgress * _Nonnull uploadProgress) {
        
        if (progress)
        {
            progress(uploadProgress);
        }
        
    } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        // 成功,关闭网络指示器
        if (success)
        {
            [UIApplication sharedApplication].networkActivityIndicatorVisible=NO;
            
            success(responseObject);
        }
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        // 失败,关闭网络指示器
        if (failure)
        {
            [UIApplication sharedApplication].networkActivityIndicatorVisible=NO;
            
            failure(error);
        }
    }];
}
@end

鉴于都说上传数据,那我贴我上传图片的代码:

[SVProgressHUD showWithStatus:@"上传中..." maskType:SVProgressHUDMaskTypeGradient];
    // 异步加载数据
    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
        NSString *url = [NSString stringWithFormat:@"%@follow/uploadPictures",RSE_URL];
        // 对userid进行加密
        NSString *token = [[NSUserDefaults standardUserDefaults] objectForKey:@"token"];
        NSString *userstr = [NSString stringWithFormat:@"%zd",[_model.cusid integerValue]];
        NSString *userid = [MSEncryptUtil encryptUseDES:userstr key:token];
        //  图片
       
        NSData *data;
        if (array.count > 0) {
            
            for(int i = 0;i< array.count;i++){
                 //  压缩图片
                data = UIImageJPEGRepresentation([array objectAtIndex:i],1.0);
                NSLog(@"压缩过的图片的文件大小 %zdKB",[data length]/1024);
                
                // 设置参数
                NSMutableDictionary *dic = [NSMutableDictionary dictionary];
                [dic setValue:userid forKey:@"cusId"];  // 客户id
                [dic setValue:_model.cusType forKey:@"cusType"]; // 客户类型
                [dic setValue:imagType forKey:@"pictureType"]; // 图片类型
                
                
                [[AFNetworkTool  sharedManager] HTTPPost:url parameters:dic formdata:^(id<AFMultipartFormData> formdata) {
                    NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
                    formatter.dateFormat = @"yyyyMMddHHmmss";
                    NSString *str = [formatter stringFromDate:[NSDate date]];
                    NSString *fileName = [NSString stringWithFormat:@"%@.png", str];
                    
                    [formdata appendPartWithFileData:data  name:@"fileName" fileName:fileName mimeType:@"image/png"];
                } progress:^(NSProgress *uploadProgress) {
                    
                } success:^(id responseObj) {
                    [SVProgressHUD dismiss];
                } failure:^(NSError *error) {
                    NSLog(@"error : %@",error);
                    [SVProgressHUD showErrorWithStatus:@"上传失败" duration:0.5];
                }];
            }
        };
        
    });

iOS技术合集
Web note ad 1