分享

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

 叹落花 2015-04-22
基本上所有的APP都会涉及网络这块,不管是用AFNetWorking还是自己写的http请求,整个网络框架的搭建很重要。
楼主封装的网络请求类,包括自己写的http请求和AFNetWorking的请求,代码简单,主要是框架搭建。简单来说,就是一个请求类,一个解析类,还有若干数据类。
以下代码以公开的天气查询api为例:
1.网络请求类
我把常用的网络请求方法都封装好了,你只需要写自己的接口,传递apiName,params等参数就可以。
#pragmamark ios请求方式
//ios自带的get请求方式
-(void)getddByUrlPath:(NSString *)path andParams:(NSString *)paramsandCallBack:(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(), ^{ idjsonData = [NSJSONSerialization JSONObjectWithData:data options:0error: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*)paramsandCallBack:(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:paramsoptions: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); idjsonData = [NSJSONSerialization JSONObjectWithData:data options:0error:Nil]; if([jsonData isKindOfClass:[NSArray class]]) { NSDictionary* dic = jsonData[0]; callback(dic); }else{ callback(jsonData); } }); }]; //开始请求
[task resume]; } }
#pragmamark 第三方请求方式
//第三方的get请求方式
-(void)getByApiName:(NSString *)apiName andParams:(id)paramsandCallBack:(CallBack)callback{ [self.manager GET:apiName parameters:paramssuccess:^(AFHTTPRequestOperation *operation, idresponseObject) { callback(responseObject); } failure:^(AFHTTPRequestOperation *operation, NSError *error) { callback(nil); }]; }
//第三方的post请求方式
-(void)postByApiName:(NSString *)apiName andParams:(id)paramsandCallBack:(CallBack)callback{ [self.manager POST:apiName parameters:paramssuccess:^(AFHTTPRequestOperation *operation, idresponseObject) { callback(responseObject); } failure:^(AFHTTPRequestOperation *operation, NSError *error) { callback(nil); }]; }
//第三方的post上传图片请求方式
-(void)postImageByApiName:(NSString *)apiName andParams:(id)paramsandImagesArray:(NSArray*)images andBack:(CallBack)callback{ [self.manager POST:apiName parameters:paramsconstructingBodyWithBlock:^(idformData) { for(inti = 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, idresponseObject) { callback(responseObject); } failure:^(AFHTTPRequestOperation *operation, NSError *error) { callback(nil); }]; }
-(void)postImageByApiName:(NSString *)apiName andImageName:(NSString*)imageName andParams:(id)paramsandImage:(UIImage*)image andBack:(CallBack)callback{ NSData* imageData = UIImageJPEGRepresentation(image, 0.8); [self.manager POST:apiName parameters:paramsconstructingBodyWithBlock:^(idformData) { [formData appendPartWithFileData:imageData name:imageName fileName:[NSString stringWithFormat:@"image.jpg"] mimeType:@"image/jpeg"]; } success:^(AFHTTPRequestOperation *operation, idresponseObject) { 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:^(idobj) { //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"]; returnweaInfo; }
3 在请求网络的地方请求
- (void)getNetData{ [[WTNetWorkingManager shareWTNetWorkingManager]getWeatherCallBack:^(idobj) { 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

    本站是提供个人知识管理的网络存储空间,所有内容均由用户发布,不代表本站观点。请注意甄别内容中的联系方式、诱导购买等信息,谨防诈骗。如发现有害或侵权内容,请点击一键举报。
    转藏 分享 献花(0

    0条评论

    发表

    请遵守用户 评论公约

    类似文章 更多