美文网首页iOS小白聚集地
AFNetworking简单的二次封装

AFNetworking简单的二次封装

作者: 今晚月色 | 来源:发表于2018-05-19 19:58 被阅读49次

    初次封装,还有待改进,希望大家批评!
    WDNetWorking.h文件

    #import <Foundation/Foundation.h>
    
    // 网络请求Block
    typedef void(^SuccessBlock)(id dicData);
    typedef void(^FaliedBlock)(id dicDta);
    
    @interface WDNetWorking : NSObject
    /**
     单例
     
     @return [[self alloc] init];
     */
    + (instancetype)share;
    // 检测网络
    + (void)monitorNetworking;
    /**
     Post请求
     
     @param url 接口名称
     @param isNeed 是否需要加载动画
     @param postDic 参数字典
     @param successBlock 成功回调
     @param faliedBlock 失败回调
     */
    + (void)PostRequestWithUrl : (NSString *)url
                    andNeedSVP : (BOOL)isNeed
                    andPostDic : (NSDictionary *)postDic
               andSuccessBlock : (SuccessBlock)successBlock
                andFaliedBlock : (FaliedBlock)faliedBlock;
    /**
     Get请求
     
     @param url 接口名称
     @param isNeed 是否需要加载动画
     @param postDic 参数字典
     @param successBlock 成功回调
     @param faliedBlock 失败回调
     */
    + (void)GetRequestWithUrl : (NSString *)url
                   andNeedSVP : (BOOL)isNeed
                   andPostDic : (NSDictionary *)postDic
              andSuccessBlock : (SuccessBlock)successBlock
               andFaliedBlock : (FaliedBlock)faliedBlock;
    /**
     单图上传
     
     @param url 接口
     @param image 图片
     @param isNeed 是否需要加载动画
     @param successBlock 成功回调
     */
    + (void)requestDataUploadWithUrl : (NSString *)url
                               Image : (UIImage *)image
                          andNeedSVP : (BOOL)isNeed
                     andSuccessBlock : (SuccessBlock)successBlock;
    /**
     多图上传
     
     @param url 接口
     @param ImagesArray 图片数组
     @param isNeed 是否需要加载动画
     @param successBlock 成功回调
     */
    + (void)multPictureUploadWithWithUrl : (NSString *)url
                             ImagesArray : (NSMutableArray *)ImagesArray
                              andNeedSVP : (BOOL)isNeed
                         andSuccessBlock : (SuccessBlock)successBlock;
    
    @end
    

    WDNetWorking.m文件

    #import "WDNetworking.h"
    #import <AFNetworking.h>
    
    #define  CurrentWindows [UIApplication sharedApplication].keyWindow
    #define  WD_SCRWIDTH    [UIScreen mainScreen].bounds.size.width
    #define  WD_SCRHEIHGT   [UIScreen mainScreen].bounds.size.height
    
    @interface WDNetWorking ()
    // AFNetWorking
    @property (nonatomic, strong) AFHTTPSessionManager *sessionManager;
    
    @end
    
    // 创建静态对象 防止外部访问
    static WDNetWorking *_instance;
    
    @implementation WDNetWorking
    
    + (instancetype)allocWithZone:(struct _NSZone *)zone{
        
        static dispatch_once_t onceToken;
        // 一次函数
        dispatch_once(&onceToken, ^{
            if (_instance == nil) {
                _instance = [super allocWithZone:zone];
            }
        });
        return _instance;
    }
    
    /**
     单例
     
     @return [[self alloc] init];
     */
    + (instancetype)share{
        
        return  [[self alloc] init];
    }
    #pragma mark --- getter && setter
    /**
     AFHTTPSessionManager
     
     @return AFHTTPSessionManager
     */
    - (AFHTTPSessionManager *)sessionManager{
        if(!_sessionManager){
            _sessionManager = [AFHTTPSessionManager manager];
            // 设置请求时间
            [_sessionManager.requestSerializer willChangeValueForKey:@"timeoutInterval"];
            _sessionManager.requestSerializer.timeoutInterval = 3.f;
            [_sessionManager.requestSerializer didChangeValueForKey:@"timeoutInterval"];
            
            _sessionManager.responseSerializer.acceptableContentTypes = [_sessionManager.responseSerializer.acceptableContentTypes setByAddingObjectsFromSet:[NSSet setWithObjects:@"text/html",@"text/plain",@"application/json",nil]];
            _sessionManager.responseSerializer = [AFHTTPResponseSerializer serializer];
            _sessionManager.requestSerializer = [AFHTTPRequestSerializer serializer];
        }
        return _sessionManager;
    }
    /**
     Post请求
     
     @param url 接口名称
     @param isNeed 是否需要加载动画
     @param postDic 参数字典
     @param successBlock 成功回调
     @param faliedBlock 失败回调
     */
    + (void)PostRequestWithUrl : (NSString *)url
                    andNeedSVP : (BOOL)isNeed
                    andPostDic : (NSDictionary *)postDic
               andSuccessBlock : (SuccessBlock)successBlock
                andFaliedBlock : (FaliedBlock)faliedBlock{
        
        // 如果有动画,动画启动
        [[WDNetWorking share].sessionManager POST:url
                             parameters:postDic
                               progress:^(NSProgress * _Nonnull uploadProgress) {
                                   
                               } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
                                   
                                   // data 转 字典
                                   NSDictionary * dict = [WDNetWorking dataConvertoDictionaryWith:responseObject];
                                   
                                   // 如果有动画,动画停止
                                   if(dict){
                                       if([dict[@"code"] integerValue]  != 0){
                                           [[WDNetWorking share] showTostWithCode:dict[@"code"]
                                                                        andMsgDic:dict];
                                           faliedBlock(dict);
                                       }else{
                                           successBlock(dict);
                                       }
                                   }
                               } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
                                   // 如果有动画,动画停止
                                   [[WDNetWorking share] showErrorTostWithErrorCode:error.code];
                               }];
    }
    
    /**
     Get请求
     
     @param url 接口名称
     @param isNeed 是否需要加载动画
     @param postDic 参数字典
     @param successBlock 成功回调
     @param faliedBlock 失败回调
     */
    + (void)GetRequestWithUrl : (NSString *)url
                   andNeedSVP : (BOOL)isNeed
                   andPostDic : (NSDictionary *)postDic
              andSuccessBlock : (SuccessBlock)successBlock
               andFaliedBlock : (FaliedBlock)faliedBlock{
        
        // 如果有动画,动画启动
        [[WDNetWorking share].sessionManager GET:url
                            parameters:postDic
                              progress:^(NSProgress * _Nonnull downloadProgress) {
                                  
                              } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
                                  // data 转 字典
                                  NSDictionary * dict = [WDNetWorking dataConvertoDictionaryWith:responseObject];
                                  
                                  // 如果有动画,动画停止
    
                                  if(dict){
                                      if([dict[@"code"] integerValue]  != 0){
                                          [[WDNetWorking share] showTostWithCode:dict[@"code"]
                                                             andMsgDic:dict[@"msg"]];
                                          faliedBlock(dict);
                                      }else{
                                          successBlock(dict);
                                      }
                                  }
                              } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
                                  // 如果有动画,动画停止
                                  [[WDNetWorking share] showErrorTostWithErrorCode:error.code];
                              }];
    }
    /**
     单图上传
     
     @param url 接口
     @param image 图片
     @param isNeed 是否需要加载动画
     @param successBlock 成功回调
     */
    + (void)requestDataUploadWithUrl : (NSString *)url
                               Image : (UIImage *)image
                          andNeedSVP : (BOOL)isNeed
                     andSuccessBlock : (SuccessBlock)successBlock{
        // 如果有动画,动画启动
        [WDNetWorking share].sessionManager.requestSerializer.timeoutInterval = 20.f;
        [[WDNetWorking share].sessionManager POST:url
                             parameters:nil
              constructingBodyWithBlock:^(id<AFMultipartFormData>  _Nonnull formData){
                  
                  NSString *fileName = [NSString  stringWithFormat:@"%@.png",[WDNetWorking currentDate]];
                  NSData *imageData = UIImageJPEGRepresentation(image, 1);
                  double scaleNum = (double)300*1024/imageData.length;
                  
                  imageData = scaleNum < 1 ? UIImageJPEGRepresentation(image, scaleNum) : UIImageJPEGRepresentation(image, 0.5);
                  
                  [formData  appendPartWithFileData:imageData
                                               name:@"file"
                                           fileName:fileName
                                           mimeType:@"image/jpg/png/jpeg"];
                  
              } progress:^(NSProgress * _Nonnull uploadProgress) {
                  
              } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
                  
                  // 如果有动画,动画停止
                  successBlock([WDNetWorking dataConvertoDictionaryWith:responseObject]);
                  
              }failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
                  
                  // 如果有动画,动画停止
                  [[WDNetWorking share] showErrorTostWithErrorCode:error.code];
              }];
    }
    
    
    /**
     多图上传
     
     @param url 接口
     @param ImagesArray 图片数组
     @param isNeed 是否需要加载动画
     @param successBlock 成功回调
     */
    + (void)multPictureUploadWithWithUrl : (NSString *)url
                             ImagesArray : (NSMutableArray *)ImagesArray
                              andNeedSVP : (BOOL)isNeed
                         andSuccessBlock : (SuccessBlock)successBlock{
        
        // 如果有动画,动画启动
        [WDNetWorking share].sessionManager.requestSerializer.timeoutInterval = 20;
        [[WDNetWorking share].sessionManager POST:url
                             parameters:nil
              constructingBodyWithBlock:^(id<AFMultipartFormData>  _Nonnull formData) {
                  
                  for (int i = 0; i < ImagesArray.count; i++) {
                      
                      UIImage  *image = [UIImage imageWithData:[NSData dataWithContentsOfURL:ImagesArray[i]]];
                      
                      NSString *dateString = [WDNetWorking currentDate];
                      
                      NSString *fileName = [NSString  stringWithFormat:@"%@.png",dateString];
                      
                      NSData *imageData = UIImageJPEGRepresentation(image, 1);
                      
                      double scaleNum = (double)300*1024/imageData.length;
                      
                      imageData = scaleNum < 1 ? UIImageJPEGRepresentation(image, scaleNum) : UIImageJPEGRepresentation(image, 0.1);
                      
                      [formData  appendPartWithFileData:imageData
                                                   name:@"files"
                                               fileName:fileName
                                               mimeType:@"image/jpg/png/jpeg"];
                  }
              }progress:^(NSProgress * _Nonnull uploadProgress) {
                  NSLog(@"%@",uploadProgress);
              }success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
                  // 如果有动画,动画停止
                  successBlock([WDNetWorking dataConvertoDictionaryWith:responseObject]);
              }failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
                  // 如果有动画,动画停止
                  [[WDNetWorking share] showErrorTostWithErrorCode:error.code];
              }];
    }
    
    /**
     获取当前时间
     @return 字符串
     */
    + (NSString *)currentDate{
        NSDate *date = [NSDate date];
        NSDateFormatter *formormat = [[NSDateFormatter alloc]init];
        [formormat setDateFormat:@"HH-mm-ss-sss"];
        return [formormat stringFromDate:date];
    }
    /**
     字典转json字符串方法
     
     @param dict 字典
     @return 字符串
     */
    + (NSString *)convertToJsonData:(NSDictionary *)dict{
        NSError *error;
        NSData *jsonData = [NSJSONSerialization dataWithJSONObject:dict
                                                           options:NSJSONWritingPrettyPrinted
                                                             error:&error];
        NSString *jsonString;
        if (!jsonData) {
            NSLog(@"字典转json字符串错误:%@",error);
        }else{
            jsonString = [[NSString alloc]initWithData:jsonData
                                              encoding:NSUTF8StringEncoding];
        }
        NSMutableString *mutStr = [NSMutableString stringWithString:jsonString];
        NSRange range = {0,jsonString.length};
        
        //去掉字符串中的空格
        [mutStr replaceOccurrencesOfString:@" "
                                withString:@""
                                   options:NSLiteralSearch range:range];
        
        NSRange range2 = {0,mutStr.length};
        
        //去掉字符串中的换行符
        [mutStr replaceOccurrencesOfString:@"\n"
                                withString:@""
                                   options:NSLiteralSearch range:range2];
        
        return mutStr;
    }
    
    /**
     data转字典
     
     @param data data
     */
    + (NSDictionary *)dataConvertoDictionaryWith:(id)data{
        
        return [NSJSONSerialization JSONObjectWithData:data
                                               options:NSJSONReadingMutableContainers | NSJSONReadingMutableLeaves
                                                 error:nil];
        
    }
    #pragma mark - ------------- 监测网络状态 -------------
    + (void)monitorNetworking
    {
        [[AFNetworkReachabilityManager sharedManager] startMonitoring];
        [[AFNetworkReachabilityManager sharedManager] setReachabilityStatusChangeBlock:^(AFNetworkReachabilityStatus status) {
            switch (status) {
                case -1:
                    NSLog(@"未知网络");
                    break;
                case 0:
                    NSLog(@"网络不可达");
                    break;
                case 1:
                {
                    NSLog(@"GPRS网络");
                }
                    break;
                case 2:
                {
                    NSLog(@"wifi网络");
                }
                    break;
                default:
                    break;
            }
            if (status == AFNetworkReachabilityStatusReachableViaWWAN || status == AFNetworkReachabilityStatusReachableViaWiFi) {
                NSLog(@"有网");
            }else{
                NSLog(@"没网");
            }
        }];
    }
    /**
     根据返回的错误code进行判断
     
     @param errorCode 错误代码
     */
    - (void)showErrorTostWithErrorCode:(NSInteger)errorCode{
        
        // 根据返回的code值 添加提示弹窗
    }
    /**
     根据返回的code进行判断
     
     @param code 非0的状态码
     */
    - (void)showTostWithCode:(NSString *)code
                   andMsgDic:(NSDictionary *)msgDic{
        
        NSInteger CODE = [code integerValue];
        if(CODE  == 1001){
            // 异地登录--token失效
            // 提示:您的账号在别地登录,请重新登录
            [self performSelector:@selector(signOut) withObject:nil afterDelay:1.0];
            
        }else{
            // 提示 服务器返回信息
        }
    }
    
    - (void)signOut{
        // TODO: 清楚用户信息、退出到登录页面
    }
    
    @end
    

    相关文章

      网友评论

      本文标题:AFNetworking简单的二次封装

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