美文网首页
13、对数据请求进行封装

13、对数据请求进行封装

作者: 深爱久随i | 来源:发表于2017-01-20 11:18 被阅读0次
    #import "NetWorkingHelper.h"
    
    
    
    @implementation NetWorkingHelper
    
    +(NSData*)dicTransformDataWithDic:(NSDictionary*)dic{
        
        NSMutableArray* mArray=[NSMutableArray array];
        if (dic && dic.count) {
            for (NSString* key in dic) {
                NSString* str=[NSString stringWithFormat:@"%@=%@",key,dic[key]];
                [mArray addObject:str];
               
            }
            NSString* resultStr=[mArray componentsJoinedByString:@"&"];
            return [resultStr dataUsingEncoding:NSUTF8StringEncoding];
        }else{
            
            return nil;
        }
        
    }
    
    
    
    //外部调用的方法
    +(void)requestWithType:(RequestType)type url:(NSString*)url parameters:(NSDictionary*)parameters success:(Success)success failure:(Failure)failure{
        //会话管理对象
        NSURLSession* session=[NSURLSession sharedSession];
        NSMutableURLRequest* req=nil;
        NSURLSessionDataTask* task=nil;
        //设置请求参数
       
        if (type==GET) {
            NSString* parString=[[NSString alloc] initWithData:[self dicTransformDataWithDic:parameters] encoding:NSUTF8StringEncoding ];
            if (parString) {
                url=[url stringByAppendingFormat:@"?%@",parString]; 
            }
           
            req=[NSMutableURLRequest requestWithURL:[NSURL URLWithString:url]];
            req.HTTPMethod=@"GET";
            
            
        }else{
           req.HTTPMethod=@"POST";
            req=[NSMutableURLRequest requestWithURL:[NSURL URLWithString:url]];
             req.HTTPBody=[self dicTransformDataWithDic:parameters];
        }
        task=[session dataTaskWithRequest:req completionHandler:^(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error) {
            if (error) {
                if (failure) {
                    //请求失败
                    failure(task,error);
                }
            }else{
                //请求成功
                id result=[NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingAllowFragments error:nil];
                if (success) {
                    success(task,result);
                }
            }
            
        }];
        //启动任务
        [task resume];
      
    }
    
    
    @end
    
    

    在其他类中调用即可,例如:

    - (void)viewDidLoad {
        [super viewDidLoad];
        NSString* url=@"http://ipad-bjwb.bjd.com.cn/DigitalPublication/publish/Handler/APINewsList.ashx?date=20151101&startRecord=1&len=5&udid=1234567890&terminalType=Iphone&cid=213";
      [NetWorkingHelper requestWithType:GET url:url parameters:nil success:^(NSURLSessionTask *task, id responseObject) {
          if (responseObject) {
              NSLog(@"请求成功----%@",responseObject);
          }
          
      } failure:^(NSURLSessionTask *task, NSError *error) {
          if (error) {
              
              NSLog(@"请求失败---%@",error.description);
          }
          
      }];
    }
    
    

    相关文章

      网友评论

          本文标题:13、对数据请求进行封装

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