美文网首页程序员
基于AFN的网络库封装

基于AFN的网络库封装

作者: AllenYukin | 来源:发表于2017-08-17 12:10 被阅读81次

    第一层 HMRequest 功能

    • HTTP 常用请求方式 GET POST PUT PATCH DELETE
    • POST 上传JSON数据
    • PHOTO 单张多张照片上传

    HMRequest.h
    #import <UIKit/UIKit.h>
    #import <Foundation/Foundation.h>
    
    @interface HMRequestModel : HMBaseModel
    @property (nonatomic, strong) NSNumber *code;
    @property (nonatomic, copy) NSString   *message;
    
    @end
    
    typedef void(^HMRequestSuccessBlock)(id result, HMRequestModel *model);
    typedef void(^HMRequestFailureBlock)(NSString *msg);
    
    typedef NS_ENUM(NSInteger, HMRequestMethod) {
        HTTP_REQUEST_TYPE_GET    = 0,
        HTTP_REQUEST_TYPE_POST   = 1,
        HTTP_REQUEST_TYPE_PUT    = 2,
        HTTP_REQUEST_TYPE_PATCH  = 3,
        HTTP_REQUEST_TYPE_DELETE = 4,
    };
    
    typedef NS_ENUM(NSInteger, HMRequestStatus) {
        HTTP_REQUEST_STATUS_FAILURE = -1,
        HTTP_REQUEST_STATUS_SUCCESS = 0
    };
    
    @interface HMRequest : NSObject
    
    #pragma mark- http request
    + (void)hm_requestActionWithUrl:(NSString *)url
                             params:(NSDictionary *)params
                             method:(HMRequestMethod)method
                            success:(HMRequestSuccessBlock)success
                            failure:(HMRequestFailureBlock)failure;
    
    #pragma mark- json request
    + (void)hm_postJsonDataWithUrl:(NSString *)url
                            params:(NSDictionary *)params
                           success:(HMRequestSuccessBlock)success
                           failure:(HMRequestFailureBlock)failure;
    
    #pragma mark- photo request
    + (void)hm_upLoadPhotoWithUrl:(NSString *)url
                           params:(NSDictionary *)params
                        photoSize:(CGSize)photoSize
                           photos:(NSArray *)photos
                          success:(HMRequestSuccessBlock)success
                          failure:(HMRequestFailureBlock)failure;
    @end
    
    
    HMRequest.m
    #import "HMRequest.h"
    
    @implementation HMRequestModel
    
    
    @end
    
    @implementation HMRequest
    
    + (void)hm_requestActionWithUrl:(NSString *)url
                             params:(NSDictionary *)params
                             method:(HMRequestMethod)method
                            success:(HMRequestSuccessBlock)success
                            failure:(HMRequestFailureBlock)failure
    {
        // [HMServerConfig HMServerAddress] 为正式/测试环境前缀可自行处理
        NSString *requestUrl = HM_FORMAT_TWO(@"%@%@", [HMServerConfig HMServerAddress], url);
        requestUrl = [requestUrl stringByAddingPercentEncodingWithAllowedCharacters:[NSCharacterSet URLQueryAllowedCharacterSet]];
        
        if (method == HTTP_REQUEST_TYPE_GET) {
            [[HMRequest manager] GET:requestUrl
                          parameters:params
                            progress:nil
                             success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
                                 HMRequestModel *model = [HMRequestModel yy_modelWithDictionary:responseObject];
                                 if ([model.code integerValue] == HTTP_REQUEST_STATUS_SUCCESS) success(responseObject, model);
                                 if ([model.code integerValue] == HTTP_REQUEST_STATUS_FAILURE) success(nil, model);
                             }
                             failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
                                 failure([HMRequest errorInfo:error]);
                             }];
        }
        if (method == HTTP_REQUEST_TYPE_POST) {
            [[HMRequest manager] POST:requestUrl
                           parameters:params progress:nil
                              success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
                                  HMRequestModel *model = [HMRequestModel yy_modelWithDictionary:responseObject];
                                  if ([model.code integerValue] == HTTP_REQUEST_STATUS_SUCCESS) success(responseObject, model);
                                  if ([model.code integerValue] == HTTP_REQUEST_STATUS_FAILURE) success(nil, model);
                              }
                              failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
                                  failure([HMRequest errorInfo:error]);
                              }];
        }
        if (method == HTTP_REQUEST_TYPE_PUT) {
            [[HMRequest manager] PUT:requestUrl
                          parameters:params
                             success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
                                 HMRequestModel *model = [HMRequestModel yy_modelWithDictionary:responseObject];
                                 if ([model.code integerValue] == HTTP_REQUEST_STATUS_SUCCESS) success(responseObject, model);
                                 if ([model.code integerValue] == HTTP_REQUEST_STATUS_FAILURE) success(nil, model);
                             }
                             failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
                                 failure([HMRequest errorInfo:error]);
                             }];
        }
        if (method == HTTP_REQUEST_TYPE_PATCH) {
            [[HMRequest manager] PATCH:requestUrl
                            parameters:params
                               success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
                                   HMRequestModel *model = [HMRequestModel yy_modelWithDictionary:responseObject];
                                   if ([model.code integerValue] == HTTP_REQUEST_STATUS_SUCCESS) success(responseObject, model);
                                   if ([model.code integerValue] == HTTP_REQUEST_STATUS_FAILURE) success(nil, model);
                               }
                               failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
                                   failure([HMRequest errorInfo:error]);
                               }];
        }
        if (method == HTTP_REQUEST_TYPE_DELETE) {
            [[HMRequest manager] DELETE:requestUrl
                             parameters:params
                                success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
                                    HMRequestModel *model = [HMRequestModel yy_modelWithDictionary:responseObject];
                                    if ([model.code integerValue] == HTTP_REQUEST_STATUS_SUCCESS) success(responseObject, model);
                                    if ([model.code integerValue] == HTTP_REQUEST_STATUS_FAILURE) success(nil, model);
                                }
                                failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
                                    failure([HMRequest errorInfo:error]);
                                }];
        }
    }
    
    + (void)hm_postJsonDataWithUrl:(NSString *)url
                            params:(NSDictionary *)params
                           success:(HMRequestSuccessBlock)success
                           failure:(HMRequestFailureBlock)failure
    {
        NSString *requestUrl = HM_FORMAT_TWO(@"%@%@", [HMServerConfig HMServerAddress], url);
        requestUrl = [requestUrl stringByAddingPercentEncodingWithAllowedCharacters:[NSCharacterSet URLQueryAllowedCharacterSet]];
        NSError *error;
        NSData *jsonData     = [NSJSONSerialization dataWithJSONObject:params options:0 error:&error];
        NSString *jsonString = [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];
        AFURLSessionManager *manager = [[AFURLSessionManager alloc] initWithSessionConfiguration:[NSURLSessionConfiguration defaultSessionConfiguration]];
        NSMutableURLRequest *request = [[AFJSONRequestSerializer serializer] requestWithMethod:@"POST" URLString:requestUrl parameters:nil error:nil];
        [request setValue:@"application/json" forHTTPHeaderField:@"Content-Type"];
        [request setValue:@"application/json" forHTTPHeaderField:@"Accept"];
        [request setHTTPBody:[jsonString dataUsingEncoding:NSUTF8StringEncoding]];
        [[manager dataTaskWithRequest:request completionHandler:^(NSURLResponse * _Nonnull response, id  _Nullable responseObject, NSError * _Nullable error) {
            if (responseObject) {
                HMRequestModel *model = [HMRequestModel yy_modelWithDictionary:responseObject];
                if ([model.code integerValue] == HTTP_REQUEST_STATUS_SUCCESS) success(responseObject, model);
                if ([model.code integerValue] == HTTP_REQUEST_STATUS_FAILURE) success(nil, model);
            } else {
                failure([HMRequest errorInfo:error]);
            }
        }] resume];
    }
    
    + (void)hm_upLoadPhotoWithUrl:(NSString *)url
                           params:(NSDictionary *)params
                        photoSize:(CGSize)photoSize
                           photos:(NSArray *)photos
                          success:(HMRequestSuccessBlock)success
                          failure:(HMRequestFailureBlock)failure
    {
        NSString *requestUrl = HM_FORMAT_TWO(@"%@%@", [HMServerConfig HMServerAddress], url);
        requestUrl = [requestUrl stringByAddingPercentEncodingWithAllowedCharacters:[NSCharacterSet URLQueryAllowedCharacterSet]];
        NSLog(@"url:%@\nparams:%@", requestUrl, params);
        AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
        manager.requestSerializer     = [AFHTTPRequestSerializer serializer];
        manager.responseSerializer    = [AFJSONResponseSerializer serializer];
        [SVProgressHUD show];
        [manager POST:requestUrl parameters:params constructingBodyWithBlock:^(id<AFMultipartFormData>  _Nonnull formData) {
            for (int i = 0; i < photos.count; i++) {
                NSData *imageData = UIImageJPEGRepresentation(photos[i], 0.6f);
                NSLog(@"upload image size: %ld k", (long)(imageData.length / 1024));
                NSDateFormatter *formatter = [NSDateFormatter new];
                formatter.dateFormat       = @"yyyyMMddHHmmss";
                NSString *imageName        = [formatter stringFromDate:[NSDate date]];
                NSString *fileName         = [NSString stringWithFormat:@"%@.jpg",imageName];
                [formData appendPartWithFileData:imageData name:@"image" fileName:fileName mimeType:@"image/jpeg"];
            }
        } progress:^(NSProgress * _Nonnull uploadProgress) {
        } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
            HMRequestModel *model = [HMRequestModel yy_modelWithDictionary:responseObject];
            if ([model.code integerValue] == HTTP_REQUEST_STATUS_SUCCESS) success(responseObject, model);
            if ([model.code integerValue] == HTTP_REQUEST_STATUS_FAILURE) success(nil, model);
            NSLog(@"responseObject:%@", responseObject);
            [SVProgressHUD dismiss];
            
        } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
            failure([HMRequest errorInfo:error]);
        }];
    }
    
    + (NSString *)errorInfo:(NSError *)error
    {
        return error.userInfo[@"message"] ? error.userInfo[@"message"] : @"网络断开连接,请稍后再试";
    }
    
    + (AFHTTPSessionManager *)manager
    {
        AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
        [manager.responseSerializer setAcceptableContentTypes:[NSSet setWithObjects:@"text/html",
                                                                @"text/css",
                                                                @"text/json",
                                                                @"text/javascript",
                                                                @"text/plain",
                                                                @"application/json",
                                                                @"application/x-javascript",
                                                                @"application/javascript",
                                                                @"application/vnd.api+json", nil]];
        return manager;
    }
    
    @end
    

    第二层 HMService 功能

    • 按模块进行category类别划分(例如HMNetService、HMNetService+mine)

    HMService.h
    #import "HMNetService.h"
    
    @interface HMNetService (mine)
    
    // 个人信息 -> 上传照片
    + (void)upLoadWithPhotos:(NSArray *)photos
                        type:(NSNumber *)type
                    complete:(MultiActionBlock)complete;
    
    @end
    
    HMService.m
    #import "HMNetService+mine.h"
    
    static NSString * const upLoadImageUrl = @"/upload/image";
    
    @implementation HMNetService (mine)
    
    + (void)upLoadWithPhotos:(NSArray *)photos
                        type:(NSNumber *)type
                    complete:(MultiActionBlock)complete
    {
        HMParams *params = [HMParams new];
        [params addParam:@"type" value:type];
        [HMRequest hm_upLoadPhotoWithUrl:upLoadImageUrl
                                  params:params.params
                               photoSize:CGSizeMake(50, 50)
                                  photos:photos
                                 success:^(id result, HMRequestModel *model) {
                                     complete(result, model, model.message);
        } failure:^(NSString *msg) {
            complete(nil, nil, msg);
        }];
    }
    

    第三层 外部调用实现功能

    • block回调,非常简洁只关注最后结果做处理

    [HMNetService upLoadWithPhotos:@[photo]
                              type:@(type)
                          complete:^(NSDictionary *result, HMRequestModel *requestModel, NSString *message) {
                     if (result) {
                        // 成功处理
                     } else {
                        // 失败处理
                     }
                     [[iToast makeText:message] show];
    }];
    

    相关文章

      网友评论

        本文标题:基于AFN的网络库封装

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