美文网首页
iOS开发中关于网络框架应用的理解

iOS开发中关于网络框架应用的理解

作者: 小弱鸡 | 来源:发表于2016-07-17 16:36 被阅读112次

    背景

    今年一月份公司产品中加入支付模块,要求对接口径加密操作,于是乎我们所有的接口都使用MD5加密各个参数,整个工程一共一百多个接口,由于之前接口过于零散(原来接口是放在每个模块的控制器中)。我花了将近一周的时间去完成这个事情,整个人都快疯掉了。于是在征求老大的意见后我们将接口全部集合在一个MKNetworkManager的文件中,在当时觉得方案还不错在接口更换时我们随时能很迅速的找到更换的接口,但是在项目需求依然在增加的情况下,文件代码越来越多,愈来愈显得臃肿。代码截图如下:


    {mk.h}.png
    {mk.m}.png

    如今文件的行数已突破2900行,越来越觉得这个错误的选择,但是面对一百多个接口实在没有勇气去更改了。

    新的方案

    三月份公司业务发展需要我们又新建一个项目,鉴于上个项目的教训。我对项目的网络请求框架作了一下集成处理:
    建一个基请求,所有的接口的数据都是有这一个部分传输过去的代码如下:

    //
    //  YWRequest.h
    //  YWCarOnline
    //
    //  Created by DeepWater on 16/3/29.
    //  Copyright  2016年 DeepWater. All rights reserved.
    //
    
    #import <Foundation/Foundation.h>
    
    
    
    @interface YWRequest : NSObject
    
    /**
     *  上传媒体文件
     *
     *  @param dediaData    文件数据
     *  @param urlString    链接
     *  @param parameter    参数
     *  @param successBlock 成功回调
     *  @param failBlock    失败回调
     */
    + (void)uploadFileWithMediaData:(NSMutableArray *)dediaData
                          URLString:(NSString*)urlString
                     ReturnDataType:(ReturnDataType)returnDataType
                          Parameter:(NSMutableDictionary*)parameter
                       SuccessBlock:(SuccessBlock)successBlock
                          FailBlock:(FailBlock)failBlock;
    /**
     *  接口获取数据方式
     *
     *  @param urlString      链接
     *  @param parameter      参数
     *  @param requestType    请求方式
     *  @param returnDataType 返回数据类型
     *  @param successBlock   成功回调
     *  @param failBlock      失败回调
     */
    + (void)requestWithURL:(NSString *)urlString
                 Parameter:(NSDictionary*)parameter
               RequestType:(RequestType) requestType
            ReturnDataType:(ReturnDataType)returnDataType
              SuccessBlock:(SuccessBlock)successBlock
                 FailBlock:(FailBlock)failBlock;
    @end
    
    

    实现文件

    //
    //  YWRequest.m
    //  YWCarOnline
    //
    //  Created by DeepWater on 16/3/29.
    //  Copyright  2016年 DeepWater. All rights reserved.
    //
    
    #import "YWRequest.h"
    /**
     *  正式环境
     */
    static NSString * const hostName        =@"正式环境接口";
    /**
     *  验收环境
     */
    static NSString * const testHostName    =@"验收环境";
    /**
     *  内部局域网
     */
    static NSString * const locailhostName  =@"内部局域网";
    
    @implementation YWRequest
    
    + (void)uploadFileWithMediaData:(NSMutableArray *)dediaData
                          URLString:(NSString*)urlString
                     ReturnDataType:(ReturnDataType)returnDataType
                          Parameter:(NSMutableDictionary*)parameter
                       SuccessBlock:(SuccessBlock)successBlock
                          FailBlock:(FailBlock)failBlock{
    #ifdef isIOS9
        
        NSString*urlStringUTF8 =[urlString stringByAddingPercentEncodingWithAllowedCharacters:[NSCharacterSet URLQueryAllowedCharacterSet]];
    #else
        NSString *urlStringUTF8 = [urlString stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
    #endif
        AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
        manager.responseSerializer = [AFJSONResponseSerializer serializer];
        manager.responseSerializer.acceptableContentTypes =[NSSet setWithObjects:@"text/html",@"text/plain",@"application/json", nil];
        [manager POST:urlStringUTF8 parameters:parameter constructingBodyWithBlock:^(id<AFMultipartFormData>  _Nonnull formData) {
        } progress:^(NSProgress * _Nonnull uploadProgress) {
            
        } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
            NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:responseObject options:NSJSONReadingAllowFragments error:nil];
            successBlock(dic);
            
        } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
            failBlock(error);
        }];
    }
    
    /**
     *  新接口
     *
     *  @param urlString      接口类型
     *  @param parameter      参数
     *  @param requestType    请求方式
     *  @param returnDataType 返回类型:1.POST 2.GET
     *  @param successBlock   成功回调
     *  @param failBlock      失败回调
     */
    + (void)requestWithURL:(NSString *)urlString
                 Parameter:(NSDictionary*)parameter
               RequestType:(RequestType) requestType
            ReturnDataType:(ReturnDataType)returnDataType
              SuccessBlock:(SuccessBlock)successBlock
                 FailBlock:(FailBlock)failBlock{
        NSString * path;
        /**
         *  0,正式环境
         *  1,测试环境
         *  2,本地环境
         */
        NSInteger netType =0;
        switch (netType) {
            case 0:
                path = [NSString stringWithFormat:@"%@%@",hostName,urlString];
                break;
            case 1:
                path = [NSString stringWithFormat:@"%@%@",testHostName,urlString];
                break;
            case 2:
                path = [NSString stringWithFormat:@"%@%@",locailhostName,urlString];
                break;
                
        }
        //    DLog(@"path===%@",path);
        AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
        manager.responseSerializer.acceptableContentTypes =[NSSet setWithObjects:@"text/html",@"text/plain",@"application/json", nil];
        manager.requestSerializer = [AFHTTPRequestSerializer serializer];
        manager.responseSerializer = [AFHTTPResponseSerializer serializer];
        manager.responseSerializer = [[AFCompoundResponseSerializer alloc] init];
        if (returnDataType==JSONData) {
            manager.responseSerializer = [AFJSONResponseSerializer serializer];
        }else{
            manager.responseSerializer = [AFXMLParserResponseSerializer serializer];
        }
        if (requestType == GETType) {
            NSString * urlString;
            if ([YWToolManager isBlankString:parameter[kurl]]) {
                urlString = [NSString stringWithFormat:@"%@",path];
            }else{
                urlString = [NSString stringWithFormat:@"%@?%@",path,parameter[kurl]];
            }
           
    #ifdef isIOS9 
            NSString*urlStringUTF8 =[urlString stringByAddingPercentEncodingWithAllowedCharacters:[NSCharacterSet URLQueryAllowedCharacterSet]];
    #else
            NSString *urlStringUTF8 = [urlString stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
    #endif  
    //            DLog(@"urlString==%@",urlString);
            [manager GET:urlStringUTF8 parameters:nil progress:^(NSProgress * _Nonnull downloadProgress) {
            } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
    //            DLog(@"%@",responseObject);
                successBlock(responseObject);
            } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
                failBlock(error);
            }];
        }else if (requestType == POSTType){
    #ifdef isIOS9
            NSString*urlStringUTF8 =[path stringByAddingPercentEncodingWithAllowedCharacters:[NSCharacterSet URLQueryAllowedCharacterSet]];
    #else
            NSString *urlStringUTF8 = [path stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
    #endif
    //        DLog(@"parameter==%@",parameter);
            [manager POST:urlStringUTF8 parameters:parameter progress:^(NSProgress * _Nonnull uploadProgress) {
            } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
    //            NSString *result = [[NSString alloc] initWithData:responseObject  encoding:NSUTF8StringEncoding];
                successBlock(responseObject);
            } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
                failBlock(error);
            }];
        }
    }
    
    

    使用文件

    //
    //  YWCarListRequest.h
    //  YWCarOnline
    //
    //  Created by DeepWater on 16/4/1.
    //  Copyright  2016年 DeepWater. All rights reserved.
    //
    
    #import <Foundation/Foundation.h>
    #import "YWRequest.h"
    typedef NS_ENUM(NSInteger,YWCarListRequestType) {
        getAllCarType,
        getDeveiceType,
        getCarDeviceLocationInfoType,
        getSearchDeviceType,
        getDeviceListType,
        getCarHistoryType,
    };
    @interface YWCarListRequest : NSObject
    
    /**
     *  车辆列表请求接口
     *
     *  @param carListRequsetType 接口类型
     *  @param parameter          参数
     *  @param requestType        请求方式
     *  @param successBlock       成功回调
     *  @param failBlock          失败回调
     */
    + (void)request:(YWCarListRequestType)carListRequsetType
          Parameter:(NSDictionary*)parameter
        RequestType:(RequestType) requestType
       SuccessBlock:(SuccessBlock)successBlock
          FailBlock:(FailBlock)failBlock;
    
    @end
    
    
    //
    //  YWCarListRequest.m
    //  YWCarOnline
    //
    //  Created by DeepWater on 16/4/1.
    //  Copyright  2016年 DeepWater. All rights reserved.
    //
    
    #import "YWCarListRequest.h"
    #import "YWDictionaryParse.h"
    /**
     *  车辆列表
     */
    static NSString *const getAllCarState           = @"GetAllVehicle";
    
    static NSString *const getDeveceList            = @"GetDeveceList";
    /**
     *  实时轨迹
     */
    static NSString *const getCarDeviceLocationInfo = @"GetCarDeviceLocationInfo";
    /**
     *  搜索页面
     */
    static NSString *const getSearchDevice          = @"SearchDevice";
    /**
     *  设备信息
     */
    static NSString *const getDeviceList            = @"GetDeviceList";
    /**
     *  历史轨迹
     */
    static NSString *const getCarHistory            = @"GetAllLocation";
    
    @implementation YWCarListRequest
    
    + (void)request:(YWCarListRequestType)carListRequsetType
          Parameter:(NSDictionary*)parameter
        RequestType:(RequestType) requestType
       SuccessBlock:(SuccessBlock)successBlock
          FailBlock:(FailBlock)failBlock{
        NSString *typeString;
        switch (carListRequsetType) {
            case getAllCarType:
            case getSearchDeviceType:
                typeString =getAllCarState;
                break;
            case getDeveiceType:
                typeString =getDeveceList;
                break;
            case getCarDeviceLocationInfoType:
                typeString =getCarDeviceLocationInfo;
                break;
            case getDeviceListType:
                typeString =getDeviceList;
                break;
            case getCarHistoryType:
                typeString =getCarHistory;
                break;
                
        }
        [YWRequest requestWithURL:typeString
                        Parameter:parameter
                      RequestType:requestType
                   ReturnDataType:JSONData
                     SuccessBlock:^(id returnValue) {
    //                     DLog(@"%@",returnValue);
            successBlock(returnValue);
        } FailBlock:^(NSError *error) {
            failBlock(error);
    //        NSString * test = [[NSString alloc]initWithData:error.userInfo[kbadRequstReason] encoding:NSUTF8StringEncoding];
    //         DLog(@"设备列表接口错误信息====%@",test);
        }];
    }
    
    @end
    

    然而在处理webservices(好消息是这玩意要被淘汰了)接口做对接时候会出现contentType:application/json问题,你需要加上manager.requestSerializer = [AFJSONRequestSerializer serializer];感谢默默_前行帮助。

    相关文章

      网友评论

          本文标题:iOS开发中关于网络框架应用的理解

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