AFNetWorking 封装

jopen 9年前

//  //  AFClient.h  //  Soufu580  //  //  Created by Cloud on 15/12/18.  //  Copyright © 2015年 Soufu580. All rights reserved.  //    #import <Foundation/Foundation.h>  #import "AFHTTPSessionManager.h"    @interface AFClient : AFHTTPSessionManager    /**   *  返回该类的一个实例   *   *  @return client;   */  +(instancetype)getHttpClient;      @end      ------      //  //  AFClient.m  //  Soufu580  //  //  Created by Cloud on 15/12/18.  //  Copyright © 2015年 Soufu580. All rights reserved.  //    /**   *  单例的   AFHTTPSessionManager      */    #import "AFClient.h"        static NSString *const BASEURL = @"https://112.64.173.178/";      @implementation AFClient      + (instancetype)getHttpClient  {      static AFClient *client = nil;      static dispatch_once_t onceToken;      dispatch_once(&onceToken, ^{          client = [[AFClient alloc] initWithBaseURL:[NSURL URLWithString:BASEURL]];          client.responseSerializer = [AFHTTPResponseSerializer serializer];          AFSecurityPolicy *securityPolicy = [AFSecurityPolicy defaultPolicy];          securityPolicy.allowInvalidCertificates = YES;          client.securityPolicy = securityPolicy;          client.responseSerializer.acceptableContentTypes=[NSSet setWithObjects:@"application/json", @"text/json", @"text/javascript",@"text/html", nil ,nil];                          });      return client;  }      @end    ---------    //  //  BHttpClient.h  //  Soufu580  //  //  Created by Cloud on 15/12/16.  //  Copyright © 2015年 Soufu580. All rights reserved.  //    #import <Foundation/Foundation.h>    @interface HttpUtil : NSObject      +(void) httpGet:(NSString *)urlPath param:(NSDictionary *) dict finish:(void (^) (NSData *date, NSDictionary *obj,NSError *error)) cb;  +(void) httpPost:(NSString *)urlPath param:(NSDictionary *) dict finish:(void (^) (NSData *date, NSDictionary *obj,NSError *error)) cb;      @end      ----------      //  //  BHttpClient.m  //  Soufu580  //  //  Created by Cloud on 15/12/16.  //  Copyright © 2015年 Soufu580. All rights reserved.  //    #import "HttpUtil.h"  #import "AFNetworking.h"  #include "NsUtil.h"  #import "AFClient.h"  #import "BaseModel.h"      static BOOL isFirst = NO;  static BOOL canCHeckNetwork = NO;    @implementation HttpUtil        +(void) httpGet:(NSString *)urlpath param:(NSDictionary *)dict finish:(void (^)(NSData *,NSDictionary *obj, NSError *))cb{            //1..检查网络连接(苹果公司提供的检查网络的第三方库 Reachability)      //AFN 在 Reachability基础上做了一个自己的网络检查的库, 基本上一样            [self checkNetWork];      //只能在监听完善之后才可以调用      BOOL isOK = [[AFNetworkReachabilityManager sharedManager] isReachable];      //BOOL isWifiOK = [[AFNetworkReachabilityManager sharedManager] isReachableViaWiFi];      //BOOL is3GOK = [[AFNetworkReachabilityManager sharedManager]isReachableViaWWAN];      //网络有问题      if(isOK == NO && canCHeckNetwork == YES){          NSError *error = [NSError errorWithDomain:@"网络错误" code:100 userInfo:nil];          cb(nil, nil,error);          return;      }            //2..实现解析  //    AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];  //    manager.responseSerializer = [AFHTTPResponseSerializer serializer];      [[AFClient getHttpClient] GET:urlpath parameters:dict success:^(NSURLSessionDataTask *task, id responseObject) {          //成功 cb是对方传递过来的对象 这里是直接调用                    NSDictionary *obj = [NSJSONSerialization JSONObjectWithData:responseObject options:NSJSONReadingMutableContainers error:nil];          cb(responseObject, [NsUtil replaceUnicode:[NsUtil  DataTOjsonString:obj]],nil);                    // cb(responseObject, [self replaceUnicode:[self DataTOjsonString:@""]],nil);      } failure:^(NSURLSessionDataTask *task, NSError *error) {          //失败          cb(nil, nil ,error);      }];  };            +(void) httpPost:(NSString *)urlpath param:(NSDictionary *)dict finish:(void (^)(NSData *,NSDictionary *obj, NSError *))cb{            //1..检查网络连接(苹果公司提供的检查网络的第三方库 Reachability)      //AFN 在 Reachability基础上做了一个自己的网络检查的库, 基本上一样            [self checkNetWork];      //只能在监听完善之后才可以调用      BOOL isOK = [[AFNetworkReachabilityManager sharedManager] isReachable];      //BOOL isWifiOK = [[AFNetworkReachabilityManager sharedManager] isReachableViaWiFi];      //BOOL is3GOK = [[AFNetworkReachabilityManager sharedManager]isReachableViaWWAN];      //网络有问题      if(isOK == NO && canCHeckNetwork == YES){          NSError *error = [NSError errorWithDomain:@"网络错误 " code:100 userInfo:nil];          cb(nil, nil,error);          return;      }            //2..实现解析  //    AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];  //    manager.responseSerializer = [AFHTTPResponseSerializer serializer];             [[AFClient getHttpClient] POST:urlpath parameters:dict success:^(NSURLSessionDataTask *task, id responseObject) {          //成功 cb是对方传递过来的对象 这里是直接调用         // NSDictionary *obj = [NSJSONSerialization JSONObjectWithData:responseObject options:NSJSONReadingMutableContainers error:nil];           NSError *err;           NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:responseObject                                                               options:NSJSONReadingMutableContainers                                                                 error:&err];                      BaseModel *baseModel = [[BaseModel alloc] initWithDictionary:dic];                                 NSLog(@"basenaem: %@",baseModel.msg);           //cb(responseObject, [NsUtil replaceUnicode:[NsUtil  DataTOjsonString:obj]],nil);  //        cb(responseObject, [self replaceUnicode:[self DataTOjsonString:@""]],nil);      } failure:^(NSURLSessionDataTask *task, NSError *error) {          //失败          cb(nil, nil ,error);      }];  };            +(BOOL ) checkNetWork{        if (isFirst == NO) {          //网络只有在startMonitoring完成后才可以使用检查网络状态          [[AFNetworkReachabilityManager sharedManager] startMonitoring];          [[AFNetworkReachabilityManager sharedManager]setReachabilityStatusChangeBlock:^(AFNetworkReachabilityStatus status) {              canCHeckNetwork = YES;          }];          isFirst = YES;      }            return canCHeckNetwork;    }              @end



//调用  -(void) testHttpMsPost{            NSString *urlPath = @"xxx/mmm.do";      NSDictionary*dict = @{@"type":@"1", @"cityId":@"310100",@"userId":@"1e55ff20a7264a0a9a3ebe02b066a5f8"};      [HttpUtil httpPost:urlPath param:dict finish:^(NSData *data,NSDictionary *obj, NSError *error) {          if (error == nil) {              //obj即为解析后的数据.              NSLog(@"parase my download json is %@",obj);          }else{              UIAlertView *av = [[UIAlertView alloc]initWithTitle:@"网络状态" message:@"亲 网络不给力" delegate:self cancelButtonTitle:@"OK" otherButtonTitles:nil, nil];              [av show];          }      }];        }



来自: http://my.oschina.net/xiahuawuyu/blog/547541