1. 程式人生 > >iOS 自己封裝的網路請求,json解析的類

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