iOS 自己封装的网络请求,json解析的类

基本上所有的APP都会涉及网络这块,不管是用AFNetWorking还是自己写的http请求,整个网络框架的搭建很重要。

楼主封装的网络请求类,包括自己写的http请求和AFNetWorking的请求,代码简单,主要是框架搭建。简单来说,就是一个请求类,一个解析类,还有若干数据类。

以下代码以公开的天气查询api为例:

1.网络请求类

我把常用的网络请求方法都封装好了,你只需要写自己的接口,传递apiName,params等参数就可以。

#pragma mark ios请求方式
//ios自带的get请求方式
-(void)getddByUrlPath:(NSString *)path andParams:(NSString *)params andCallBack:(CallBack)callback{

    if (params) {
        [path stringByAppendingString:[NSString stringWithFormat:@"?%@",params]];
    }
    
    NSString*  pathStr = [path  stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
    NSLog(@"url:%@",pathStr);
    NSURL *url = [NSURL URLWithString:pathStr];
    
    NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
    
    NSURLSession *session = [NSURLSession sharedSession];
    NSURLSessionDataTask *task = [session dataTaskWithRequest:request completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) {
        dispatch_async(dispatch_get_main_queue(), ^{
            
            
            id jsonData = [NSJSONSerialization JSONObjectWithData:data options:0 error:Nil];
            NSLog(@"%@",jsonData);
            
            if ([jsonData  isKindOfClass:[NSArray  class]]) {
                NSDictionary*  dic = jsonData[0];
                
                callback(dic);
                
                
            }else{
                callback(jsonData);
            }
            
        });
        
        
    }];
    //开始请求
    [task resume];
}
//ios自带的post请求方式
-(void)postddByByUrlPath:(NSString *)path andParams:(NSDictionary*)params andCallBack:(CallBack)callback{
    
    NSURL *url = [NSURL URLWithString:path];
    
    NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
    [request setHTTPMethod:@"POST"];
    NSError*  error;
    
    if ([NSJSONSerialization isValidJSONObject:params]) {
        NSData *jsonData = [NSJSONSerialization dataWithJSONObject:params options:NSJSONWritingPrettyPrinted error:&error];
        [request  setHTTPBody:jsonData];
        
        
        NSURLSession *session = [NSURLSession sharedSession];
        NSURLSessionDataTask *task = [session dataTaskWithRequest:request completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) {
            dispatch_async(dispatch_get_main_queue(), ^{
                NSString*  str = [[NSString   alloc]initWithData:data encoding:NSUTF8StringEncoding];
                NSLog(@"..........%@",str);
                id  jsonData = [NSJSONSerialization JSONObjectWithData:data options:0 error:Nil];
                if ([jsonData  isKindOfClass:[NSArray  class]]) {
                    NSDictionary*  dic = jsonData[0];
                    
                    callback(dic);
                    
                    
                }else{
                    callback(jsonData);
                }
            });
            
        }];
        //开始请求
        [task resume];
        
    }
}


#pragma mark 第三方请求方式
//第三方的get请求方式
-(void)getByApiName:(NSString *)apiName andParams:(id)params andCallBack:(CallBack)callback{
    [self.manager GET:apiName parameters:params success:^(AFHTTPRequestOperation *operation, id responseObject) {
        
        callback(responseObject);
        
    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
        
        callback(nil);

    }];
    
}
//第三方的post请求方式
-(void)postByApiName:(NSString *)apiName andParams:(id)params andCallBack:(CallBack)callback{
    
    [self.manager POST:apiName parameters:params success:^(AFHTTPRequestOperation *operation, id responseObject) {
        
        callback(responseObject);
    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
        
        callback(nil);
        
    }];
    
}
//第三方的post上传图片请求方式
-(void)postImageByApiName:(NSString *)apiName andParams:(id)params  andImagesArray:(NSArray*)images andBack:(CallBack)callback{
    [self.manager POST:apiName parameters:params constructingBodyWithBlock:^(id formData) {
        
        for (int i = 0; i<images.count; i++) {
            
            NSData*  imageData = UIImageJPEGRepresentation(images[i], 0.8);
            NSString*  name =nil;
            if (images.count == 1) {
                name = @"imageFile";
            }else{
                name = [NSString   stringWithFormat:@"file%d",i+1];
            }
            [formData appendPartWithFileData:imageData name:name fileName:[NSString stringWithFormat:@"image.jpg"] mimeType:@"image/jpeg"];
        }
        
    } success:^(AFHTTPRequestOperation *operation, id responseObject) {
        
        callback(responseObject);
        
    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
        callback(nil);
        
    }];
}


-(void)postImageByApiName:(NSString *)apiName  andImageName:(NSString*)imageName  andParams:(id)params  andImage:(UIImage*)image andBack:(CallBack)callback{
    NSData*  imageData = UIImageJPEGRepresentation(image, 0.8);
    
    [self.manager POST:apiName parameters:params constructingBodyWithBlock:^(id formData) {
        [formData appendPartWithFileData:imageData name:imageName fileName:[NSString stringWithFormat:@"image.jpg"] mimeType:@"image/jpeg"];
    } success:^(AFHTTPRequestOperation *operation, id responseObject) {
        callback(responseObject);
    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
        
        callback(nil);
        
    }];
}

以天气查询为例,自己写个接口,选择请求方式:

-(void)getWeatherCallBack:(CallBack)callback{

   
    //选择需要的请求方式,我们采用非第三方的get请求,具体情况选择不同的请求方式,都是异步请求

    [self getddByUrlPath:@"http://m.weather.com.cn/data/101190101.html" andParams:nil andCallBack:^(id obj) {
        
        //json解析
        weather* weatherInfo = [WTParseWeather parseWeatherByWeatherDic:obj];
        //返回解析后的数据
        callback(weatherInfo);

    }];
    
  
}

2 解析类,这个不同的数据要不同的解析类,自己写,这个是天气的例子:

+(weather *)parseWeatherByWeatherDic:(NSDictionary *)Dic{

    NSDictionary* weatherInfoDic = [Dic objectForKey:@"weatherinfo"];
    
    weather* weaInfo = [[weather alloc]init];
    
    weaInfo.city = [weatherInfoDic objectForKey:@"city"];
    weaInfo.date = [weatherInfoDic objectForKey:@"date_y"];
    weaInfo.week = [weatherInfoDic objectForKey:@"week"];
    weaInfo.wind = [weatherInfoDic objectForKey:@"wind1"];
    weaInfo.weather = [weatherInfoDic objectForKey:@"weather1"];
    weaInfo.tip = [weatherInfoDic objectForKey:@"index"];
    
    return weaInfo;
}

3 在请求网络的地方请求

- (void)getNetData{

    [[WTNetWorkingManager shareWTNetWorkingManager]getWeatherCallBack:^(id obj) {
        
        weather* weaInfo = obj;
        
        self.weatherInfo = weaInfo;
        
        [self giveValue];
    }];
}

- (void)giveValue{

    self.city.text = self.weatherInfo.city;
    self.date.text = self.weatherInfo.date;
    self.week.text = self.weatherInfo.week;
    self.wind.text = self.weatherInfo.wind;
    self.weather.text = self.weatherInfo.weather;
    self.tips.text = self.weatherInfo.tip;
    self.tips.userInteractionEnabled=NO;
}

我封装的类可以去我github拿:https://github.com/wangdachui

posted @ 2014-12-23 13:26  6度XZ  阅读(949)  评论(0编辑  收藏  举报