新AFNetworking使用

-(void)get
{
    AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
    [manager.securityPolicy setAllowInvalidCertificates:YES];
    manager.responseSerializer.acceptableContentTypes = [NSSet setWithObjects:@"application/json", @"text/json", @"text/javascript",@"text/html", nil];
    [manager GET:URL parameters:@{@"getKey_1":@"getValue1",@"getKey_2":@"getValue2"} progress:^(NSProgress * _Nonnull downloadProgress) {
        
        NSLog(@"is begin?");
        
    }success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        
        NSLog(@"这里打印请求成功要做的事 %@",responseObject);
        
    }failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull   error) {
        
        NSLog(@"%@",error);  //这里打印错误信息
        
    }];
}
 
-(void)post
{
    AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
    
    manager.responseSerializer.acceptableContentTypes = [NSSet setWithObjects:@"application/json", @"text/json", @"text/javascript",@"text/html", nil];
    
    NSDictionary *parameters = @{@"postKey_1":@"postValue_1",@"postKey_2":@"postValue_2"};
    
    [manager POST:URL parameters:parameters progress:^(NSProgress * _Nonnull uploadProgress) {
        NSLog(@"uploadProgress- - - %@  %lf",uploadProgress,uploadProgress.fractionCompleted);
        NSLog(@"%@   %lld",@"begin?",uploadProgress.completedUnitCount/uploadProgress.totalUnitCount);
    } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        NSLog(@"%@",responseObject);
        
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        NSLog(@"%@",error);
    }];
}
 
 
- (void)upload
{
    AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
    manager.responseSerializer.acceptableContentTypes = [NSSet setWithObjects:@"application/json", @"text/json", @"text/javascript",@"text/html", nil];
    NSDictionary *parameters = @{@"uploadKey_1":@"uploadValue_1",@"uploadKey_2":@"uploadValue_2"};
    
    [manager POST:URL parameters:parameters constructingBodyWithBlock:^(id<AFMultipartFormData>  _Nonnull formData) {
        UIImage *iamge = [UIImage imageNamed:@"IMG_0022.JPG"];
        NSData *data = UIImagePNGRepresentation(iamge);
        [formData appendPartWithFileData:data name:@"file" fileName:@"IMG_0022.JPG" mimeType:@"image/png"];
        
    } progress:^(NSProgress * _Nonnull uploadProgress) {
        NSLog(@"进度- - -%lf",uploadProgress.fractionCompleted);
    } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        
        NSLog(@"请求成功:%@",responseObject);
        
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        
        NSLog(@"请求失败:%@",error);
    }];
    
}

二次封装:

//
//  AFNetworkingOperate.h
//  MuslimFriendProject
//
//  Created by skyzizhu on 2016/11/18.
//  Copyright © 2016年 skyzizhu. All rights reserved.
//
 
#import <Foundation/Foundation.h>
 
#import "AFNetworking.h"
 
@interface AFNetworkingOperate : NSObject
 
//无httpheader get请求
+(void)GetRequestWithUrl:(NSString *)url atParams:(NSDictionary *)params atProgress:(void(^)(NSProgress *requestProgress))progress atSucceed:(void(^)(NSURLSessionDataTask *task, id responseObject))succeed atFailure:(void(^)(NSURLSessionDataTask *task, NSError *error))failure;
 
//有httpheader get请求
+(void)GetRequestAddHttpHeaderWithHttpHeader:(NSDictionary *)httpHeader atContentType:(NSString *)contentType atUrl:(NSString *)url atParams:(NSDictionary *)params atProgress:(void(^)(NSProgress *requestProgress))progress atSucceed:(void(^)(NSURLSessionDataTask *task, id responseObject))succeed atFailure:(void(^)(NSURLSessionDataTask *task, NSError *error))failure;
 
 
//无httpheader POST请求
+(void)PostRequestWithUrl:(NSString *)url atParams:(NSDictionary *)params atProgress:(void(^)(NSProgress *requestProgress))progress atSucceed:(void(^)(NSURLSessionDataTask *task, id responseObject))succeed atFailure:(void(^)(NSURLSessionDataTask *task, NSError *error))failure;
 
//有httpheader POST请求
+(void)PostRequestAddHttpHeaderWithHttpHeader:(NSDictionary *)httpHeader atContentType:(NSString *)contentType atUrl:(NSString *)url atParams:(NSDictionary *)params atProgress:(void(^)(NSProgress *requestProgress))progress atSucceed:(void(^)(NSURLSessionDataTask *task, id responseObject))succeed atFailure:(void(^)(NSURLSessionDataTask *task, NSError *error))failure;
 
//无httpheader upload file请求,主要为图片上传
+(void)UploadFileWithUrl:(NSString *)url atParams:(NSDictionary *)params atDatas:(NSArray *)datas atFileKeys:(NSArray *)fileKeys atProgress:(void(^)(NSProgress *requestProgress))progress atSucceed:(void(^)(NSURLSessionDataTask *task, id responseObject))succeed atFailure:(void(^)(NSURLSessionDataTask *task, NSError *error))failure;
 
//有httpHeader upload 上传文件
+(void)UploadFileAddConstraintWithHttpHeader:(NSDictionary *)httpHeader atUrl:(NSString *)url atParams:(NSDictionary *)params atDatas:(NSArray *)datas atFileKeys:(NSArray *)fileKeys atMimeType:(NSString *)mimeType atFileNames:(NSArray *)fileNames atContentType:(NSString *)contentType atProgress:(void(^)(NSProgress *requestProgress))progress atSucceed:(void(^)(NSURLSessionDataTask *task, id responseObject))succeed atFailure:(void(^)(NSURLSessionDataTask *task, NSError *error))failure;
 
+(void)PostRequestWithUrl:(NSString *)url atParams:(NSDictionary *)params atBeginHandle:(void (^)())beginHandle atSucceed:(void (^)(NSURLSessionDataTask *task, id responseObject))succeed atFailure:(void (^)(NSURLSessionDataTask *task, NSError *error))failure;
 
@end
//
//  AFNetworkingOperate.m
//  MuslimFriendProject
//
//  Created by skyzizhu on 2016/11/18.
//  Copyright © 2016年 skyzizhu. All rights reserved.
//
 
#import "AFNetworkingOperate.h"
 
static NSString *DefaultFileSuffix = @".png";
 
static NSString *DefaultMimeType = @"image/jpeg";
 
@implementation AFNetworkingOperate
 
//初始化AFHTTPSessionManager
+(AFHTTPSessionManager *)initAFnetworkingManagerWithContentType:(NSString *)contentType atHttpHeaderField:(NSDictionary *)headerField
{
    AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
    
    [manager.securityPolicy setAllowInvalidCertificates:YES];
    
    if(contentType == nil){
        manager.responseSerializer.acceptableContentTypes = [NSSet setWithObjects:@"application/json", @"text/json", @"text/javascript",@"text/html", nil];
    }else{
        manager.responseSerializer.acceptableContentTypes = [NSSet setWithObject:contentType];
    }
    
    if(headerField == nil){
        //public operate by httpheader
    }else{
        for (NSString *key in headerField) {
            
            [manager.requestSerializer setValue:[headerField valueForKey:key] forHTTPHeaderField:key];
        }
    }
    return manager;
}
 
//无httpheader get请求
+(void)GetRequestWithUrl:(NSString *)url atParams:(NSDictionary *)params atProgress:(void(^)(NSProgress *requestProgress))progress atSucceed:(void(^)(NSURLSessionDataTask *task, id responseObject))succeed atFailure:(void(^)(NSURLSessionDataTask *task, NSError *error))failure
{
    AFHTTPSessionManager *manager = [self initAFnetworkingManagerWithContentType:nil atHttpHeaderField:nil];
    [manager GET:[self encodeUrl:url] parameters:params progress:^(NSProgress * _Nonnull downloadProgress) {
        
        progress(downloadProgress);
        
    }success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        
        succeed(task,responseObject);
        
    }failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull   error) {
        
        failure(task,error);
        
    }];
}
 
//有httpheader get请求
+(void)GetRequestAddHttpHeaderWithHttpHeader:(NSDictionary *)httpHeader atContentType:(NSString *)contentType atUrl:(NSString *)url atParams:(NSDictionary *)params atProgress:(void(^)(NSProgress *requestProgress))progress atSucceed:(void(^)(NSURLSessionDataTask *task, id responseObject))succeed atFailure:(void(^)(NSURLSessionDataTask *task, NSError *error))failure
{
    AFHTTPSessionManager *manager = [self initAFnetworkingManagerWithContentType:contentType atHttpHeaderField:httpHeader];
    [manager GET:[self encodeUrl:url] parameters:params progress:^(NSProgress * _Nonnull downloadProgress) {
        
        progress(downloadProgress);
        
    }success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        
        succeed(task,responseObject);
        
    }failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull   error) {
        
        failure(task,error);
        
    }];
}
 
//无httpheader POST请求
+(void)PostRequestWithUrl:(NSString *)url atParams:(NSDictionary *)params atProgress:(void(^)(NSProgress *requestProgress))progress atSucceed:(void(^)(NSURLSessionDataTask *task, id responseObject))succeed atFailure:(void(^)(NSURLSessionDataTask *task, NSError *error))failure
{
    AFHTTPSessionManager *manager = [self initAFnetworkingManagerWithContentType:nil atHttpHeaderField:nil];
    
    [manager POST:[self encodeUrl:url] parameters:params progress:^(NSProgress * _Nonnull uploadProgress) {
        
        progress(uploadProgress);
        
    } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        
        succeed(task,responseObject);
        
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        
        failure(task,error);
        
    }];
}
 
//有httpheader POST请求
+(void)PostRequestAddHttpHeaderWithHttpHeader:(NSDictionary *)httpHeader atContentType:(NSString *)contentType atUrl:(NSString *)url atParams:(NSDictionary *)params atProgress:(void(^)(NSProgress *requestProgress))progress atSucceed:(void(^)(NSURLSessionDataTask *task, id responseObject))succeed atFailure:(void(^)(NSURLSessionDataTask *task, NSError *error))failure
{
    AFHTTPSessionManager *manager = [self initAFnetworkingManagerWithContentType:contentType atHttpHeaderField:httpHeader];
    
    [manager POST:[self encodeUrl:url] parameters:params progress:^(NSProgress * _Nonnull uploadProgress) {
        
        progress(uploadProgress);
        
    } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        
        succeed(task,responseObject);
        
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        
        failure(task,error);
        
    }];
}
 
//无httpheader upload file请求
+(void)UploadFileWithUrl:(NSString *)url atParams:(NSDictionary *)params atDatas:(NSArray *)datas atFileKeys:(NSArray *)fileKeys atProgress:(void(^)(NSProgress *requestProgress))progress atSucceed:(void(^)(NSURLSessionDataTask *task, id responseObject))succeed atFailure:(void(^)(NSURLSessionDataTask *task, NSError *error))failure
{
    AFHTTPSessionManager *manager = [self initAFnetworkingManagerWithContentType:nil atHttpHeaderField:nil];
    [manager POST:[self encodeUrl:url] parameters:params constructingBodyWithBlock:^(id<AFMultipartFormData>  _Nonnull formData) {
        
        if(fileKeys == nil || [fileKeys count] <= 0){
            for (int i = 0; i < [datas count]; i++) {
                [formData appendPartWithFileData:datas[i] name:[NSString stringWithFormat:@"file_%@",@(i + 1)] fileName:[NSString stringWithFormat:@"UploadFile_%@%@",@(i + 1),DefaultFileSuffix] mimeType:DefaultMimeType];
            }
        }else{
            for (int i = 0; i < [datas count]; i++) {
                [formData appendPartWithFileData:datas[i] name:fileKeys[i] fileName:[NSString stringWithFormat:@"UploadFile_%@%@",@(i + 1),DefaultFileSuffix] mimeType:DefaultMimeType];
            }
        }
        
    } progress:^(NSProgress * _Nonnull uploadProgress) {
        progress(uploadProgress);
    } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        
        succeed(task,responseObject);
        
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        
        failure(task,error);
    }];
    
}
 
+(void)UploadFileAddConstraintWithHttpHeader:(NSDictionary *)httpHeader atUrl:(NSString *)url atParams:(NSDictionary *)params atDatas:(NSArray *)datas atFileKeys:(NSArray *)fileKeys atMimeType:(NSString *)mimeType atFileNames:(NSArray *)fileNames atContentType:(NSString *)contentType atProgress:(void(^)(NSProgress *requestProgress))progress atSucceed:(void(^)(NSURLSessionDataTask *task, id responseObject))succeed atFailure:(void(^)(NSURLSessionDataTask *task, NSError *error))failure
{
    AFHTTPSessionManager *manager = [self initAFnetworkingManagerWithContentType:contentType atHttpHeaderField:httpHeader];
    [manager POST:[self encodeUrl:url] parameters:params constructingBodyWithBlock:^(id<AFMultipartFormData>  _Nonnull formData) {
        NSString *fileMimeType = mimeType == nil ? DefaultMimeType : mimeType;
        if(fileKeys == nil || [fileKeys count] <= 0){
            if(fileNames == nil || [fileNames count] <= 0){
                for (int i = 0; i < [datas count]; i++) {
                    [formData appendPartWithFileData:datas[i] name:[NSString stringWithFormat:@"file_%@",@(i + 1)] fileName:[NSString stringWithFormat:@"%@%@",@(i + 1),DefaultFileSuffix] mimeType:fileMimeType];
                }
            }else{
                for (int i = 0; i < [datas count]; i++) {
                    [formData appendPartWithFileData:datas[i] name:[NSString stringWithFormat:@"file_%@",@(i + 1)] fileName:fileNames[i] mimeType:fileMimeType];
                }
            }
        }else{
            if(fileNames == nil || [fileNames count] <= 0){
                for (int i = 0; i < [datas count]; i++) {
                    [formData appendPartWithFileData:datas[i] name:fileKeys[i] fileName:[NSString stringWithFormat:@"%@%@",@(i + 1),DefaultFileSuffix] mimeType:fileMimeType];
                }
            }else{
                for (int i = 0; i < [datas count]; i++) {
                    [formData appendPartWithFileData:datas[i] name:fileKeys[i] fileName:fileNames[i] mimeType:fileMimeType];
                }
            }
        }
        
    } progress:^(NSProgress * _Nonnull uploadProgress) {
        if(progress != nil){
            progress(uploadProgress);
        }
    } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        
        succeed(task,responseObject);
        
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        
        failure(task,error);
    }];
}
 
+(void)PostRequestWithUrl:(NSString *)url atParams:(NSDictionary *)params atBeginHandle:(void (^)())beginHandle atSucceed:(void (^)(NSURLSessionDataTask *task, id responseObject))succeed atFailure:(void (^)(NSURLSessionDataTask *task, NSError *error))failure
{
    if(beginHandle != nil){
        beginHandle();
    }
    
    AFHTTPSessionManager *manager = [self initAFnetworkingManagerWithContentType:nil atHttpHeaderField:@{@"token":[UserDefaultsOperate getLoginToken]}];
    
    [manager POST:[self encodeUrl:url] parameters:params progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        
        debug(@"%@",responseObject);
        
        succeed(task,responseObject);
        
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        
        failure(task,error);
        
    }];
}
 
 
 
//格式化URL
+(NSString *)encodeUrl:(NSString *)sourceURL
{
    if (System_Version_Later(9.0)) {
        return [sourceURL stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
    }else{
        return [sourceURL stringByAddingPercentEncodingWithAllowedCharacters:[NSCharacterSet characterSetWithCharactersInString:@"`#%^{}\"[]|\\<> "].invertedSet];
    }
}
 
@end

Leave a Reply

Required fields are marked *