基于 AFN 3.0 封装(包括图片与视频的表单上传)

1,884 阅读3分钟
原文链接: blog.csdn.net

1、首先将AFN最新的包导入工程,可以使用cocopods。
2、新建一个类,我的类名GlobalNetWorking。首先封装了一下判断是否有网,具体代码如下
GlobalNetWorking.h

#import 
#import "AFNetworking.h"
@interface GlobalNetWorking : NSObject

+(BOOL)isHasNetwork;

GlobalNetWorking.m中实现:

+(AFNetworkReachabilityStatus)currentNetworkStatus{
    static AFNetworkReachabilityStatus currentNetworkStatus = AFNetworkReachabilityStatusUnknown;
    static dispatch_once_t predicate;
    dispatch_once(&predicate, ^{
       
        [[AFNetworkReachabilityManager sharedManager] startMonitoring];
        [[AFNetworkReachabilityManager sharedManager] setReachabilityStatusChangeBlock:^(AFNetworkReachabilityStatus status) {
            currentNetworkStatus = status;
        }];
    });
    return currentNetworkStatus;
}
+(BOOL)isHasNetwork{
    BOOL flag = YES;
    AFNetworkReachabilityStatus statue = [self currentNetworkStatus];
    
    if (statue == AFNetworkReachabilityStatusUnknown || statue == AFNetworkReachabilityStatusNotReachable) {
        flag = NO;
    }
    return flag;
}

3、普通post网络请求。
GlobalNetWorking.h中:


+(void)networkWithPhpStr:(NSString *)phpStr andParametersString:(NSString *)parameters andSuccess:(void (^)(id rootObject, id datasObject, bool isSuccess))success andFailure:(void (^)(NSError *error))failure;

GlobalNetWorking.m中
这里的+(NSDictionary *)createPostParameterDictionaryWithUrlString:(NSString *)urlStr;这个类方法是将我上面所说的传给后台数据拼接的parameters字符串转化为字典。(所以这一步在上面可以省略,直接传入字典。)

#pragma mark - 解析生成post参数
+(NSDictionary *)createPostParameterDictionaryWithUrlString:(NSString *)urlStr
{
    if (!urlStr || ![urlStr isKindOfClass:[NSString class]]) {
        return nil;
    }
    NSArray *tmpAndArray = [urlStr componentsSeparatedByString:@"&"];
    NSMutableDictionary *tmpDic = [[NSMutableDictionary alloc] init];
    for (NSString *tmpString in tmpAndArray) {
        if (![tmpString isKindOfClass:[NSString class]]) {
            continue;
        } 
        NSArray *tmpEqualArray = [tmpString componentsSeparatedByString:@"="];
        if (tmpEqualArray.count == 2) {
            NSString *tmpKey = [NSString stringWithFormat:@"%@", tmpEqualArray[0]];
            NSString *tmpValue = [NSString stringWithFormat:@"%@", tmpEqualArray[1]];
            [tmpDic setValue:tmpValue forKey:tmpKey];
        }

    }
    return tmpDic;
}
+(void)networkWithPhpStr:(NSString *)phpStr andParametersString:(NSString *)parameters andSuccess:(void (^)(id rootObject, id datasObject, bool isSuccess))success andFailure:(void (^)(NSError *error))failure
{
    AFHTTPSessionManager *sessionManager = [AFHTTPSessionManager manager];
    sessionManager.responseSerializer = [AFHTTPResponseSerializer serializer];
    NSDictionary *params = [self createPostParameterDictionaryWithUrlString:parameters];
    
    [sessionManager POST:[NSString stringWithFormat:@"%@%@",HTTP_AFNETWORKING_POST_URL,phpStr] parameters:params progress:^(NSProgress * _Nonnull uploadProgress) {

    } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        NSDictionary *rootDic = [NSJSONSerialization JSONObjectWithData:responseObject options:NSJSONReadingMutableContainers error:nil];
        
        if (!rootDic || ![rootDic isKindOfClass:[NSDictionary class]] || ![rootDic.allKeys containsObject:@"data"]) {
            NSError * error = [[NSError alloc] initWithDomain:@"datasError" code:ErrorCodeNoDatasKey userInfo:@{NSLocalizedDescriptionKey:@"网络请求返回值没有datas字段!"}];
            failure(error);
            return;
        }
        id datasValue = [rootDic objectForKey:@"data"];
        BOOL isSuccess = [[rootDic valueForKey:@"status"] boolValue];
        success(rootDic,datasValue,isSuccess);

    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        failure(error);
    }];
}

4、进行图片上传的封装。
首先看一下我这里的需求:需要进行表单上传,其次是多张图片需要放在数组中。
代码如下:
GlobalNetWorking.h中:


+(void)uploadImageWithPhpStr:(NSString *)phpStr andParametersString:(NSString *)parameters andImageArray:(NSArray *)imageArray andSuccess:(void (^)(id rootObject, id datasObject, bool isSuccess))success andFailure:(void (^)(NSError *error))failure;

GlobalNetWorking.m中具体实现:

+(void)uploadImageWithPhpStr:(NSString *)phpStr andParametersString:(NSString *)parameters andImageArray:(NSArray *)imageArray andSuccess:(void (^)(id, id, bool))success andFailure:(void (^)(NSError *))failure{
    AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
    manager.responseSerializer = [AFHTTPResponseSerializer serializer];
    NSDictionary *params = [self createPostParameterDictionaryWithUrlString:parameters];
    NSLog(@"%@",params);
    [manager POST:[NSString stringWithFormat:@"%@%@",HTTP_AFNETWORKING_POST_URL,phpStr] parameters:params constructingBodyWithBlock:^(id  _Nonnull formData) {
        NSUInteger i = 0 ;
        for (UIImage *image in imageArray) {
            NSData * imgData = UIImageJPEGRepresentation(image, .5);
            
             
            [formData appendPartWithFileData:imgData name:[NSString stringWithFormat:@"pic[%ld]",(long)i] fileName:@"image.png" mimeType:@"image/jpg"];
            i++;
        }
    } progress:^(NSProgress * _Nonnull uploadProgress) {

    } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        NSDictionary *rootDic = [NSJSONSerialization JSONObjectWithData:responseObject options:NSJSONReadingMutableContainers error:nil];
        if (!rootDic || ![rootDic isKindOfClass:[NSDictionary class]] || ![rootDic.allKeys containsObject:@"data"]) {
            NSError * error = [[NSError alloc] initWithDomain:@"datasError" code:ErrorCodeNoDatasKey userInfo:@{NSLocalizedDescriptionKey:@"网络请求返回值没有data字段!"}];
            failure(error);
            return;
        }
        id datasValue = [rootDic objectForKey:@"data"];
        BOOL isSuccess = [[rootDic valueForKey:@"status"] boolValue];
        success(rootDic,datasValue,isSuccess);

    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        failure(error);
    }];
}

5、视频上传的方法
视频上传和图片上传大同小异。具体如下:
GlobalNetWorking.h中:
这里我将video转换成NSData进行上传的。


+(void)uploadVideoWithPhpStr:(NSString *)phpStr andParametersString:(NSString *)parameters andVideoData:(NSData *)videoData andSuccess:(void (^)(id rootObject, id datasObject, bool isSuccess))success andFailure:(void (^)(NSError *error))failure;

GlobalNetWorking.m中具体实现:

+(void)uploadVideoWithPhpStr:(NSString *)phpStr andParametersString:(NSString *)parameters andVideoData:(NSData *)videoData andSuccess:(void (^)(id, id, bool))success andFailure:(void (^)(NSError *))failure{
    AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
    manager.responseSerializer = [AFHTTPResponseSerializer serializer];
    NSDictionary *params = [self createPostParameterDictionaryWithUrlString:parameters];
    NSLog(@"%@",params);
    [manager POST:[NSString stringWithFormat:@"%@%@",HTTP_AFNETWORKING_POST_URL,phpStr] parameters:params constructingBodyWithBlock:^(id  _Nonnull formData) {
        [formData appendPartWithFileData:videoData name:@"video" fileName:@"video.mp4" mimeType:@"video/mp4"];

    } progress:^(NSProgress * _Nonnull uploadProgress) {

    } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        NSDictionary *rootDic = [NSJSONSerialization JSONObjectWithData:responseObject options:NSJSONReadingMutableContainers error:nil];
        if (!rootDic || ![rootDic isKindOfClass:[NSDictionary class]] || ![rootDic.allKeys containsObject:@"data"]) {
            NSError * error = [[NSError alloc] initWithDomain:@"datasError" code:ErrorCodeNoDatasKey userInfo:@{NSLocalizedDescriptionKey:@"网络请求返回值没有data字段!"}];
            failure(error);
            return;
        }
        id datasValue = [rootDic objectForKey:@"data"];
        BOOL isSuccess = [[rootDic valueForKey:@"status"] boolValue];
        success(rootDic,datasValue,isSuccess);

    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        failure(error);
    }];

}

以上就是AFN 3.0 的简单的再次封装。如果有什么问题请留言,有错请指出,谢谢。