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: error:Nil];
NSLog(@"%@",jsonData); if ([jsonData isKindOfClass:[NSArray class]]) {
NSDictionary* dic = jsonData[]; 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: error:Nil];
if ([jsonData isKindOfClass:[NSArray class]]) {
NSDictionary* dic = jsonData[]; 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 = ; i<images.count; i++) { NSData* imageData = UIImageJPEGRepresentation(images[i], 0.8);
NSString* name =nil;
if (images.count == ) {
name = @"imageFile";
}else{
name = [NSString stringWithFormat:@"file%d",i+];
}
[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
iOS 自己封装的网络请求,json解析的类的更多相关文章
- IOS SWIFT 网络请求JSON解析 基础一
前言:移动互联网时代,网络通信已经是手机端必不可少的功能.应用中也必不可少地使用了网络通信,增强客户端与服务器交互.使用NSURLConnection实现HTTP的通信.NSURLConnection ...
- Win(Phone)10开发第(3)弹,简单的Demo程序网络请求json解析列表显示
先分享一个由Json字符串直接生成解析对应的类的工具: jsonclassgenerator14 百度天气接口 下面是由一个小功能(又特么的是天气)的实现,记录下下UAP的流程和结构(其实跟之前一模一 ...
- 基于AFNetworking封装的网络请求工具类【原创】
今天给大家共享一个我自己封装的网络请求类,希望能帮助到大家. 前提,导入AFNetworking框架, 关于修改AFN源码:通常序列化时做对text/plan等的支持时,可以一劳永逸的修改源代码,在a ...
- C#字符串数组排序 C#排序算法大全 C#字符串比较方法 一个.NET通用JSON解析/构建类的实现(c#) C#处理Json文件 asp.net使用Jquery+iframe传值问题
C#字符串数组排序 //排序只带字符的数组,不带数字的 private string[] aa ={ "a ", "c ", "b & ...
- 一个.NET通用JSON解析/构建类的实现(c#)转
转自:http://www.cnblogs.com/xfrog/archive/2010/04/07/1706754.html NET通用JSON解析/构建类的实现(c#) 在.NET Framewo ...
- 一个.NET通用JSON解析/构建类的实…
一个.NET通用JSON解析/构建类的实现(c#) 在.NET Framework 3.5中已经提供了一个JSON对象的序列化工具,但是他是强类型的,必须先按JSON对象的格式定义一个类型,并将类型加 ...
- iOS开发——post异步网络请求封装
IOS中有许多网络请求的函数,同步的,异步的,通过delegate异步回调的. 在做一个项目的时候,上网看了很多别人的例子,发现都没有一个简单的,方便的异步请求的封装例子.我这里要给出的封装代码,是异 ...
- 移动开发在路上-- IOS移动开发 五 网络请求封装
接着上次的讲,这次我们讲 网络请求的封装 打开创建的项目,让我们一起来继续完成他, 上次我们说到GET请求地址的拼接: 我们接着上次的继续完善: 下边我们要定义的是 block //定义block ...
- iOS项目中的网络请求和上下拉刷新封装
代码地址如下:http://www.demodashi.com/demo/11621.html 一.运行效果图 现在的项目中不可避免的要使用到网络请求,而且几乎所有软件都有上下拉刷新功能,所以我在此对 ...
随机推荐
- elasticsearch6.6.0安装配置及elasticsearch-head插件安装
一.最小化安装centos7.6 cat /etc/redhat-release 二.配置网络,可以上外网 三.安装常用命令工具,修改系统时区,校对系统时间,关闭selinux,关闭firewalld ...
- Algorithms学习笔记-Chapter0序言
0.开篇 <Algorithms>源自Berkeley和UCSD课程讲义,由 Sanjoy Dasgupta / Christos H. Papadimitriou / Umesh V ...
- 公钥与私钥的理解,以及https的应用原理
1.公钥与私钥原理1)鲍勃有两把钥匙,一把是公钥,另一把是私钥2)鲍勃把公钥送给他的朋友们----帕蒂.道格.苏珊----每人一把.3)苏珊要给鲍勃写一封保密的信.她写完后用鲍勃的公钥加密,就可以达到 ...
- django反向解析URL和URL命名空间
django反向解析URL和URL命名空间 首先明确几个概念: 1.在html页面上的内容特别是向用户展示的url地址,比如常见的超链接,图片链接等,最好能动态生成,而不要固定. 2.一个django ...
- 铁大快捷记账Alpha版使用说明书
一. 引言 (1) 编写目的 (2) 参考资料 (3) 术语和缩写词 二. 网站概述 (1) 网站用途 (2) 网站运行 三. 网站使用过程 (1)网站登录 (2) 功能说明 一.引言 (1)编写目的 ...
- Linux 信号:signal 与 sigaction
0.Linux下查看支持的信号列表: france@Ubuntux64:~$ kill -l ) SIGHUP ) SIGINT ) SIGQUIT ) SIGILL ) SIGTRAP ) SIGA ...
- AD分辨率和精度区别
最近做了一块板子,当然考虑到元器件的选型了,由于指标中要求精度比较高,所以对于AD的选型很慎重.很多人对于精度和分辨率的概念不清楚,这里我做一下总结,希望大家不要混淆.我们搞电子开发的,经常跟“精度” ...
- helm的安装于与简单使用
根据 csdn 博客整理学习 原始博客地址: https://blog.csdn.net/weiguang1017/article/details/78045013 1. 下载所需要的文件: 客户端文 ...
- MacOS 如何剪切文件
MacOS 如何剪切文件 MacOS 剪切文件 command + C 复制 command + V 粘贴 删除 & 粘贴 在 Windows中 Ctrl + X 是剪切,MacOS中没有剪切 ...
- JavaFile类和递归
八.File类和递归 8.1 概述 java.io.File 类时文件和目录路径名的抽象表示,主要用于文件和目录的创建.查找和产出等操作. 8.2 构造方法 public File(String pa ...