AFNetworking3.0的网络封装初级2016.10

1.导入AFNetworking 3.0的框架
手动下载,并且拖动文件夹到工程
或者用pod工具
2.封装get方式、post方式请求数据


3.新建一个类CJNetworking
CJNetworking.h

#import 
  
typedef enum{
    StatusUnknown           = -1,   //未知网络
    StatusNotReachable      = 0,    //没有网络
    StatusReachableViaWWAN  = 1,    //手机自带网络2G,3G,4G
    StatusReachableViaWiFi  = 2     //wifi
}NetworkStatus;

typedef void( ^ CJResponseSuccess)(id response);
typedef void( ^ CJResponseFail)(NSError *error);
/**
 *  方便管理请求任务。执行取消,暂停,继续等任务.
 */
typedef NSURLSessionTask CJURLSessionTask;


@interface CJNetworking : NSObject
/**
 *  获取网络状态
 */
@property (nonatomic,assign)NetworkStatus networkStats;
/**
 *  网络共享的单例对象
 */
+ (CJNetworking *)sharedCJNetworking;
/**
 *  网络监测
 */
+ (void)startMonitoring;


/**
 *  get请求方法,block回调
 *
 *  @param url     请求连接,根路径
 *  @param params  参数
 *  @param success 请求成功返回数据
 *  @param fail    请求失败
 *  @param showHUD 是否显示HUD
 */
+(CJURLSessionTask *)getWithUrl:(NSString *)url
                         params:(NSDictionary *)params
                        success:(CJResponseSuccess)success
                           fail:(CJResponseFail)fail
                        showHUD:(BOOL)showHUD;

/**
 *  post请求方法,block回调
 *
 *  @param url     请求连接,根路径
 *  @param params  参数
 *  @param success 请求成功返回数据
 *  @param fail    请求失败
 *  @param showHUD 是否显示HUD
 */
+(CJURLSessionTask *)postWithUrl:(NSString *)url
                          params:(NSDictionary *)params
                         success:(CJResponseSuccess)success
                            fail:(CJResponseFail)fail
                         showHUD:(BOOL)showHUD;
@end

CJNetworking.m文件

pragma mark 类似懒加载

//单例
+(CJNetworking *)sharedCJNetworking{
    static CJNetworking *handler = nil;
    
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        handler = [[CJNetworking alloc]init];
    });
    return handler;
}

+(NSMutableArray *)tasks{
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        tasks = [[NSMutableArray alloc]init];
    });
    return tasks;
}

网络监控

+ (void)startMonitoring
{
    // 1.获得网络监控的管理者
    AFNetworkReachabilityManager *mgr = [AFNetworkReachabilityManager sharedManager];
    // 2.设置网络状态改变后的处理
    [mgr setReachabilityStatusChangeBlock:^(AFNetworkReachabilityStatus status) {
        // 当网络状态改变了, 就会调用这个block
        switch (status)
        {
            case AFNetworkReachabilityStatusUnknown: // 未知网络
                DLog(@"未知网络");
                [CJNetworking sharedCJNetworking].networkStats=StatusUnknown;
                
                break;
            case AFNetworkReachabilityStatusNotReachable: // 没有网络(断网)
                DLog(@"没有网络");
                [CJNetworking sharedCJNetworking].networkStats=StatusNotReachable;
                break;
            case AFNetworkReachabilityStatusReachableViaWWAN: // 手机自带网络
                DLog(@"手机自带网络");
                [CJNetworking sharedCJNetworking].networkStats=StatusReachableViaWWAN;
                break;
            case AFNetworkReachabilityStatusReachableViaWiFi: // WIFI
                
                [CJNetworking sharedCJNetworking].networkStats=StatusReachableViaWiFi;
                DLog(@"WIFI--%d",[CJNetworking sharedCJNetworking].networkStats);
                break;
        }
    }];
    [mgr startMonitoring];
}

AFNetworking管理者

+(AFHTTPSessionManager *)getAFManager{
    [AFNetworkActivityIndicatorManager sharedManager].enabled = YES;
    
    AFHTTPSessionManager *manager = manager = [AFHTTPSessionManager manager];
    manager.responseSerializer = [AFJSONResponseSerializer serializer];//设置返回数据为json
    manager.requestSerializer.stringEncoding = NSUTF8StringEncoding;
    manager.requestSerializer.timeoutInterval=10;
    manager.responseSerializer.acceptableContentTypes = [NSSet setWithArray:@[@"application/json",
                                                                              @"text/html",
                                                                              @"text/json",
                                                                              @"text/plain",
                                                                              @"text/javascript",
                                                                              @"text/xml",
                                                                              @"image/*"]];

    return manager;
    
}

//

//GET请求,baseRequestType为1
+ (CJURLSessionTask *)getWithUrl:(NSString *)url
                          params:(NSDictionary *)params
                         success:(CJResponseSuccess)success
                            fail:(CJResponseFail)fail
                         showHUD:(BOOL)showHUD {
     return [self baseRequestType:1 url:url params:params success:success fail:fail showHUD:showHUD];
}
//POST请求,baseRequestType为2
+(CJURLSessionTask *)postWithUrl:(NSString *)url
                          params:(NSDictionary *)params
                         success:(CJResponseSuccess)success
                            fail:(CJResponseFail)fail
                         showHUD:(BOOL)showHUD{
    return [self baseRequestType:2 url:url params:params success:success fail:fail showHUD:showHUD];
}

//执行请求的过程

+(CJURLSessionTask *)baseRequestType:(NSUInteger)type
                                 url:(NSString *)url
                              params:(NSDictionary *)params
                             success:(CJResponseSuccess)success
                                fail:(CJResponseFail)fail
                             showHUD:(BOOL)showHUD{
    
    DLog(@"请求地址----%@\n    请求参数----%@",url,params);
    if (url==nil) {
        return nil;
    }
    
    if (showHUD==YES) {
        [MBProgressHUD showHUD];
    }
 
    
    AFHTTPSessionManager *manager=[self getAFManager];
    
    CJURLSessionTask *sessionTask=nil;
    
    if (type==1) {
        sessionTask = [manager GET:url parameters:params progress:^(NSProgress * _Nonnull downloadProgress) {
            
        } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
             DLog(@"请求结果=%@",responseObject);
            if (success) {
                success(responseObject);
            }
            
            [[self tasks] removeObject:sessionTask];
            
            if (showHUD==YES) {
                [MBProgressHUD dissmiss];
            }
            
        } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
            DLog(@"error=%@",error);
            if (fail) {
                fail(error);
            }
            
            [[self tasks] removeObject:sessionTask];
            
            if (showHUD==YES) {
                [MBProgressHUD dissmiss];
            }
            
        }];
        
    }else{
        
        sessionTask = [manager POST:url parameters:params progress:^(NSProgress * _Nonnull uploadProgress) {
            
        } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
            DLog(@"请求成功=%@",responseObject);
            if (success) {
                success(responseObject);
            }
            
            [[self tasks] removeObject:sessionTask];
            
            if (showHUD==YES) {
                [MBProgressHUD dissmiss];
            }
            
        } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
            DLog(@"error=%@",error);
            if (fail) {
                fail(error);
            }
            
            [[self tasks] removeObject:sessionTask];
            
            if (showHUD==YES) {
                [MBProgressHUD dissmiss];
            }
            
        }];
        
        
    }
    
    if (sessionTask) {
        [[self tasks] addObject:sessionTask];
    }
    
    return sessionTask;
    
}

你可能感兴趣的:(AFNetworking3.0的网络封装初级2016.10)