本人就iOS开发中常见的网络数据解析方式以及使用情况做了汇总,希望阅读者能够从中受益.....
为了便于分析,本人就直接搞了一个新闻接口 通过解析并输出其中数据来确保操作正确性,好了 闲话不多说了,咱们就直接进入正题。
一、准备操作
首先我们修改工程的Info.plist文件 //xcode 7 之后若想要使用HTTP 需要修改info.plist文件 这一点大家看图就会明白
继而
@interface ViewController ()//三个代理这里选中DataDelegate
@property(nonatomic,strong)NSMutableArray *dataArray;//存放解析完成数据的数组
//定以一个可变data 数据
@property(nonatomic,strong)NSMutableData *tempData;
@end
//新闻接口
#define BASE_URL @"http://ipad-bjwb.bjd.com.cn/DigitalPublication/publish/Handler/APINewsList.ashx?date=20131129&startRecord=1&len=5&udid=1234567890&terminalType=Iphone&cid=213"
//将上面的字符串分段为以 ? 为分界线分为两部分
#define URL_POST1 @"http://ipad-bjwb.bjd.com.cn/DigitalPublication/publish/Handler/APINewsList.ashx"
#define URL_POST2 @"date=20131129&startRecord=1&len=5&udid=1234567890&terminalType=Iphone&cid=213"
//懒加载初始化数组
-(NSMutableArray *)dataArray{
if (_dataArray == nil) {
_dataArray =[NSMutableArray array];
}
return _dataArray;
}
二、网络数据解析方式和用法
1、Get同步解析
- (IBAction)getTongbu:(UIButton *)sender {
NSLog(@"=============Get同步");
//创建url对象
NSURL *url = [NSURL URLWithString:BASE_URL];
//创建请求对象
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
//设置请求方式 这一步可以不写 默认设置为get请求
[request setHTTPMethod:@"get"];
//创建相应对象
NSURLResponse *response = nil;
NSError *error;
//创建连接对象
NSData *data = [NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&error];
NSDictionary *dict = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingAllowFragments error:&error];
// NSLog(@"%@",dict);
NSArray *array =dict[@"news"];
for (NSDictionary *dic in array) {
NewsModel *model =[NewsModel new];
[model setValuesForKeysWithDictionary:dic];
[self.dataArray addObject:model];
}
for (NewsModel *model in _dataArray) {
NSLog(@"%@",model);
}
}
2、Post同步解析
- (IBAction)postTongbu:(UIButton *)sender {
NSLog(@"=============Post同步");
//创建url对象
NSURL *url = [NSURL URLWithString:URL_POST1];
//创建请求对象
NSMutableURLRequest *request =[NSMutableURLRequest requestWithURL:url];
//设置请求方式
[request setHTTPMethod:@"post"];//get可以进行省略 但是post不能省略
//设置请求参数
NSData *tempData =[URL_POST2 dataUsingEncoding:NSUTF8StringEncoding];
[request setHTTPBody:tempData];
//创建响应对象
NSURLResponse *responde = nil;
//创建连接对象
NSError *error;
NSData *data = [NSURLConnection sendSynchronousRequest:request returningResponse: &responde error:&error];
NSDictionary *dict =[NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingAllowFragments error:&error];
NSArray *arary =dict[@"news"];
for (NSDictionary *dic in arary) {
NewsModel *model =[NewsModel new];
[model setValuesForKeysWithDictionary:dic];
[self.dataArray addObject:model];
}
for (NewsModel *model in _dataArray) {
NSLog(@"%@",model);
}
}
3、Get异步Block
- (IBAction)getYiBlock:(id)sender {
NSLog(@"=============Get异步Block");
NSURL *url =[NSURL URLWithString:BASE_URL];
NSMutableURLRequest *request =[NSMutableURLRequest requestWithURL:url];
[request setHTTPMethod:@"get"];
__weak typeof(self)temp = self;
[NSURLConnection sendAsynchronousRequest:request queue:[NSOperationQueue mainQueue] completionHandler:^(NSURLResponse * _Nullable response, NSData * _Nullable data, NSError * _Nullable connectionError) {
NSError *error;
NSDictionary *dict =[NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingAllowFragments error:&error];
NSArray *array =dict[@"news"];
for (NSDictionary *dic in array) {
NewsModel *model = [NewsModel new];
[model setValuesForKeysWithDictionary:dic];
[temp.dataArray addObject:model];
}
for (NewsModel *model in temp.dataArray) {
NSLog(@"%@",model);
}
}];
}
4、Post异步Block
- (IBAction)postYoBlock:(id)sender {
NSLog(@"=============Post异步Block同步");
NSURL *url = [NSURL URLWithString:URL_POST1];
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
NSURLResponse *responde = nil;
[request setHTTPMethod:@"post"];
NSData *tempData = [URL_POST2 dataUsingEncoding:NSUTF8StringEncoding];
[request setHTTPBody:tempData];
__weak typeof(self)temp =self;
[NSURLConnection sendAsynchronousRequest:request queue:[NSOperationQueue mainQueue] completionHandler:^(NSURLResponse * _Nullable response, NSData * _Nullable data, NSError * _Nullable connectionError) {
NSError *error;
NSDictionary *dict = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingAllowFragments error:&error];
NSArray *array = dict[@"news"];
for (NSDictionary *dic in array) {
NewsModel *model =[NewsModel new];
[model setValuesForKeysWithDictionary:dic];
[temp.dataArray addObject:model];
}
for (NewsModel *model in temp.dataArray) {
NSLog(@"%@",model);
}
}];
}
除以上之外,还有Get的Delegate方式请求和Post的Delegate方式请求,这两种方式都需要遵守 NSURLConnectionDataDelegate协议,并实现协议里面的几个方法才能进行数据操作的实现 ,以下两种方式的实现都是在此基础上进行的
5、Get异步Delegate
- (IBAction)getYiDelegate:(UIButton *)sender {
NSLog(@"Get异步请求代理");
//创建url对象
NSURL *url =[NSURL URLWithString:BASE_URL];
//创建请求对象
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
//创建连接对象并实现代理
NSURLConnection *connection =[NSURLConnection connectionWithRequest:request delegate:self];
//开始执行
[connection start];
}
6、Post异步Delegate
- (IBAction)postYiDelegate:(id)sender {
NSLog(@"Post异步请求代理");
NSURL *url =[NSURL URLWithString:URL_POST1];
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
[request setHTTPMethod:@"post"];
NSData *tempData =[URL_POST2 dataUsingEncoding:NSUTF8StringEncoding];
[request setHTTPBody:tempData];
NSURLConnection *connection =[NSURLConnection connectionWithRequest:request delegate:self];
[connection start];
}
NSURLConnectionDataDelegate方法的实现
//接收到服务器响应的时候出发的方法
-(void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response{
//准备数据接收 先进行数据初始化
self.tempData =[NSMutableData data];
}
//接收请求的数据
-(void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data{
//将每次接收到的数据拼接到原有数据包的后面
[_tempData appendData:data];
}
//数据加载完毕 开始解析
-(void)connectionDidFinishLoading:(NSURLConnection *)connection{
NSError *error;
NSDictionary *dict =[NSJSONSerialization JSONObjectWithData:_tempData options:NSJSONReadingAllowFragments error:&error];
NSArray *array =dict[@"news"];
for (NSDictionary *dic in array) {
NewsModel *model =[NewsModel new];
[model setValuesForKeysWithDictionary:dic];
[self.dataArray addObject:model];
}
for (NewsModel *model in _dataArray) {
NSLog(@"%@",model);
}
}
//打印失败信息
-(void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error{
NSLog(@"文件连接出现了error = %@",error);
}
7、Get Session异步请求
- (IBAction)getSession:(UIButton *)sender {
//准备url对象
NSURL *url =[NSURL URLWithString:BASE_URL];
//创建session对象
NSURLSession *session =[NSURLSession sharedSession];
__weak typeof(self)temp =self;
//创建task(该方法内部默认使用get)直接进行传递url即可
NSURLSessionDataTask *dataTask =[session dataTaskWithURL:url completionHandler:^(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error) {
temp.dataArray = [NSMutableArray arrayWithCapacity:1];
//数据操作
NSDictionary *dic =[NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingAllowFragments error:nil];
NSArray *array =dic[@"news"];
for (NSDictionary *dict in array) {
NewsModel *model = [NewsModel new];
[model setValuesForKeysWithDictionary:dict];
[temp.dataArray addObject:model];
}
}];
//数据操作
[dataTask resume];
for (NewsModel *model in _dataArray) {
NSLog(@"%@",model);
}
}
8、Post Session异步请求
- (IBAction)postSession:(UIButton *)sender {
NSLog(@"postSession-异步请求");
//创建URL对象
NSURL *url =[NSURL URLWithString:URL_POST1];
//创建请求对象
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
[request setHTTPMethod:@"post"];
NSData *tempdata = [URL_POST2 dataUsingEncoding:NSUTF8StringEncoding];
[request setHTTPBody:tempdata];
// 3 建立会话 session支持三种类型的任务
// NSURLSessionDataTask //加载数据
// NSURLSessionDownloadTask //下载
// NSURLSessionUploadTask //上传
NSURLSession *session =[NSURLSession sharedSession];
// NSLog(@"%d",[[NSThread currentThread] isMainThread]);
__weak typeof(self)temp = self;
NSURLSessionDataTask *dataTask = [session dataTaskWithRequest:request completionHandler:^(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error) {
//解析
_dataArray = [NSMutableArray arrayWithCapacity:1];
NSDictionary *dic =[NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingAllowFragments error:nil];
NSArray *array =dic[@"news"];
for (NSDictionary *dict in array) {
NewsModel *model = [NewsModel new];
[model setValuesForKeysWithDictionary:dict];
[_dataArray addObject:model];
}
// NSLog(@"%@",dic);
// NSLog(@"%d----",[[NSThread currentThread] isMainThread]);
//回到主线程 刷新数据 要是刷新就在这里面
dispatch_async(dispatch_get_main_queue(), ^{
// [temp.tableView reloadData];
for (NewsModel *model in _dataArray) {
NSLog(@"%@",model);
}
});
}];
//启动任务
[dataTask resume];
}
好了,以上就是这篇文章的所有内容,笔者在此表示感谢~~~~~