封装AFNetworking
jopen
10年前
实现AFNetworking 的高封装
//1.将AFNetworking的业务封装到了MyHttpDownLoad类中(.h和.m文件已给出)赋值即可使用
//2.调用方法-(void)testAFNetworking; 该方法中的网址是我内网的网址,使用者可以换成自己的JSON请求的网址
//3.最后APPDelegate中还要写一句 [[AFNetworkReachabilityManager sharedManager] startMonitoring];监听网络状态
APPDelegate里还要设置一下 //监听网络状态,只调用一次 [[AFNetworkReachabilityManager sharedManager] startMonitoring];
#import <Foundation/Foundation.h> @interface MyHttpDownLoad : NSObject //cb callback回调 +(void) download:(NSString *)urlpath param:(NSDictionary *)dict finish:( void (^)(NSData *data,NSDictionary *obj, NSError *error))cb; @end #import "MyHttpDownLoad.h" #import "AFNetworking.h" static BOOL isFirst = NO; static BOOL canCHeckNetwork = NO; @implementation MyHttpDownLoad +(void) download:(NSString *)urlpath param:(NSDictionary *)dict finish:(void (^)(NSData *,NSDictionary *obj, NSError *))cb{ //1..检查网络连接(苹果公司提供的检查网络的第三方库 Reachability) //AFN 在 Reachability基础上做了一个自己的网络检查的库, 基本上一样 if (isFirst == NO) { //网络只有在startMonitoring完成后才可以使用检查网络状态 [[AFNetworkReachabilityManager sharedManager] startMonitoring]; [[AFNetworkReachabilityManager sharedManager]setReachabilityStatusChangeBlock:^(AFNetworkReachabilityStatus status) { canCHeckNetwork = YES; }]; isFirst = YES; } //只能在监听完善之后才可以调用 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]; [manager GET:urlpath parameters:dict success:^(NSURLSessionDataTask *task, id responseObject) { //成功 cb是对方传递过来的对象 这里是直接调用 NSDictionary *obj = [NSJSONSerialization JSONObjectWithData:responseObject options:NSJSONReadingMutableContainers error:nil]; cb(responseObject, obj ,nil); } failure:^(NSURLSessionDataTask *task, NSError *error) { //失败 cb(nil, nil ,error); }]; }; @end
//2.调用方式 -(void)testAFNetworking{ NSString *urlPath = @"http://10.0.8.8/sns/my/user_list.php"; NSDictionary *params = @{@"page" : @"10"}; [MyHttpDownLoad download:urlPath param:params 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]; } }]; }