[NSURLSession/Delegate]用Post方式获取网络数据并把数据显示到表格
#pragma mark 实现NSURLSessionDataDelegate代理
@interface ViewController ()<UITableViewDataSource,UITableViewDelegate,NSURLSessionDataDelegate>
{
UIButton* sessionPostButton;
UIButton* sessionDelegatePostButton;
UITableView* table;
NSMutableArray* array;
NSMutableData* mutableData;
}
@end @implementation ViewController - (void)viewDidLoad {
[super viewDidLoad]; sessionPostButton=[[UIButton alloc]initWithFrame:CGRectMake(, , , )];
sessionPostButton.backgroundColor=[UIColor orangeColor];
[sessionPostButton setTitle:@"Session" forState:UIControlStateNormal];
[sessionPostButton addTarget:self action:@selector(sessionPostData) forControlEvents:UIControlEventTouchUpInside]; sessionDelegatePostButton=[[UIButton alloc]initWithFrame:CGRectMake(, , , )];
sessionDelegatePostButton.backgroundColor=[UIColor orangeColor];
[sessionDelegatePostButton setTitle:@"Delegate" forState:UIControlStateNormal];
[sessionDelegatePostButton addTarget:self action:@selector(sessionDelegatePostData) forControlEvents:UIControlEventTouchUpInside]; table=[[UITableView alloc]initWithFrame:CGRectMake(, , , -) style:UITableViewStylePlain];
table.dataSource=self;
table.delegate=self; [self.view addSubview:table];
[self.view addSubview:sessionPostButton];
[self.view addSubview:sessionDelegatePostButton];
} - (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section;
{
return array.count;
} #pragma mark 表示每一行显示什么数据
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath;
{
//内存优化
static NSString * identity=@"cell";
//tableview 根据标识复制出一个cell
UITableViewCell * cell=[tableView dequeueReusableCellWithIdentifier:identity];
if (cell==nil) {
cell=[[UITableViewCell alloc]initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:identity];
}
NSDictionary* dic=array[indexPath.row];
cell.textLabel.text=[dic valueForKey:@"title"];
cell.detailTextLabel.text=[dic valueForKey:@"type"];
cell.accessoryType=UITableViewCellAccessoryDisclosureIndicator;
return cell;
} -(void)sessionPostData
{
NSLog(@"sessionPost");
//创建NSString用来存储请求的网址
NSString* str=@"http://ipad-bjwb.bjd.com.cn/DigitalPublication/publish/Handler/APINewsList.ashx";
//用UTF8String格式转换成NSURL
NSURL* url=[NSURL URLWithString:[str stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]];
//创建请求
NSMutableURLRequest* request=[[NSMutableURLRequest alloc]initWithURL:url];
[request setHTTPMethod:@"POST"];
//设置参数
NSString* where=@"date=20131129&startRecord=1&len=5&udid=1234567890&terminalType=Iphone&cid=213";
NSData* data=[where dataUsingEncoding:NSUTF8StringEncoding];
[request setHTTPBody:data];
//创建session对象 单例
NSURLSession* session=[NSURLSession sharedSession];
//发送请求
NSURLSessionTask* task=[session dataTaskWithRequest:request completionHandler:^(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error) {
if (data) {
//处理数据
NSDictionary* dic=[NSJSONSerialization JSONObjectWithData:data options: error:nil];
array=[dic valueForKey:@"news"];
[table reloadData];
}
if (error) {
NSLog(@"%@",[error description]);
}
}];
[task resume];
} -(void)sessionDelegatePostData
{
NSLog(@"sessionDelegatePost");
//创建NSString用来存储请求的网址
NSString* str=@"http://ipad-bjwb.bjd.com.cn/DigitalPublication/publish/Handler/APINewsList.ashx";
//用UTF8String格式转换成NSURL
NSURL* url=[NSURL URLWithString:[str stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]];
//创建请求
NSMutableURLRequest* request=[[NSMutableURLRequest alloc]initWithURL:url];
[request setHTTPMethod:@"POST"];
//设置参数
NSString* where=@"date=20131129&startRecord=1&len=5&udid=1234567890&terminalType=Iphone&cid=213";
NSData* data=[where dataUsingEncoding:NSUTF8StringEncoding];
[request setHTTPBody:data];
//默认的session配置 从网络读取数据
NSURLSessionConfiguration* config=[NSURLSessionConfiguration defaultSessionConfiguration];
//遵守delegate
NSURLSession* session=[NSURLSession sessionWithConfiguration:config delegate:self delegateQueue:nil];
//发送请求
NSURLSessionDataTask* task=[session dataTaskWithRequest:request];
//初始化接收数据的容器
mutableData=[NSMutableData data];
//开始任务
[task resume];
} #pragma mark NSURLSessionDataDelegate中的方法
//#pragma mark 是否收到服务器响应 该方法不实现 实现后和后面方法冲突 用来测试服务器响应使用
//- (void)URLSession:(NSURLSession *)session dataTask:(NSURLSessionDataTask *)dataTask
//didReceiveResponse:(NSURLResponse *)response
// completionHandler:(void (^)(NSURLSessionResponseDisposition disposition))completionHandler;
//{
// NSLog(@"连接服务器成功");
//} #pragma mark 服务器开始传输数据 反复调用本方法
- (void)URLSession:(NSURLSession *)session dataTask:(NSURLSessionDataTask *)dataTask
didReceiveData:(NSData *)data;
{
NSLog(@"正在传输数据");
[mutableData appendData:data];
} #pragma mark 客户端接收数据完成时调用此方法
- (void)URLSession:(NSURLSession *)session dataTask:(NSURLSessionDataTask *)dataTask
willCacheResponse:(NSCachedURLResponse *)proposedResponse
completionHandler:(void (^)(NSCachedURLResponse * __nullable cachedResponse))completionHandler;
{
NSLog(@"数据传输完成");
NSDictionary* dic=[NSJSONSerialization JSONObjectWithData:mutableData options:NSJSONReadingMutableContainers error:nil];
array=[dic valueForKey:@"news"];
[table reloadData];
}
[NSURLSession/Delegate]用Post方式获取网络数据并把数据显示到表格的更多相关文章
- [NSURLConnection]分别用Post和Get方式获取网络数据并把数据显示到表格
@interface ViewController ()<UITableViewDataSource,UITableViewDelegate> { UIButton* getButton; ...
- Http方式获取网络数据
通过以下代码可以根据网址获取网页的html数据,安卓中获取网络数据的时候会用到,而且会用Java中的sax方式解析获取到数据.(sax解析主要是解析xml)具体代码如下: package com.wy ...
- 用 get 同步/异步 方式获取网络数据并输出
//同步请求 //创建NSString用来存储请求的网址 NSString* str=@"http://v.juhe.cn/weather/index?format=2&cityna ...
- android—获取网络数据
取网络数据主要靠发交易(或者说请求,接口等),而这些交易由java中的网络通信,HttpURLConnection和HttpClient实现,以下是具体例子. 大家都知道,网络通信,发送请求有两种 ...
- 使用NSURLSession获取网络数据和下载文件
使用NSURLSession获取网络数据 使用NSURLSession下载文件
- 使用promise方式来获取网络数据
获取网络数据 let data = []; new Promise(function(resolve,reject){ axios.post('api.php').then(function(resp ...
- Swift - 异步获取网络数据封装类
使用NSURLConnection.sendAsynchronousRequest()可以采用异步获取的方式取得数据.下面通过对数据获取类进行封装,演示如何进行数据请求与接收. 1,HttpContr ...
- Windows Phone 同步方式获取网络类型
原文:Windows Phone 同步方式获取网络类型 在Windows Phone 开发中有时候需要获取设备当前连接网络的类型,是Wifi,还是2G,3G,或者4G,SDK中提供获取网络类型的API ...
- Android简易实战教程--第四十七话《使用OKhttp回调方式获取网络信息》
在之前的小案例中写过一篇使用HttpUrlConnection获取网络数据的例子.在OKhttp盛行的时代,当然要学会怎么使用它,本篇就对其基本使用做一个介绍,然后再使用它的接口回调的方式获取相同的数 ...
随机推荐
- 几种常用的JS类定义方法(转)
// 方法1 对象直接量 var obj1 = { v1 : "", get_v1 : function() { return this.v1; }, set_v1 : funct ...
- 江湖救急:webbrowser中js文件丢失问题~
页面中,有一个按钮,点击按钮通过js create 了一个 script标签 ,链接加载一个外部js文件,执行该js文件 $("#a").click(function(){ $.g ...
- springMVC 缓存(入门 spring+mybaties+redis一)
使用redis之前需要咋电脑上安装redis: 使用spring+mybaties+redis的本质是扩展类 org.apache.ibatis.cache.Cache:在我们自己扩展的Cache ...
- iOS创建子工程
实际开发中,我们可能会同时开发好几个端,比如楼主目前开发的家教平台,需要老师端,家长端,助教端三个端.有很多工具方法,或者封装的自定义控件都是可以复用的.我们就可以把公用的代码抽取出去,新建一个工程, ...
- BSA基础数据维护
平台 BSA基础数据维护 .扇区五个字段的内容 本来值为0,经过107上计算解析,得出正常的数值.然后106上报(200050),得到回复(200051). 查看回复数据,是否有错误.比如提示104 ...
- html 补充
替换文本属性(Alt)alt 属性用来为图像定义一串预备的可替换的文本.替换文本属性的值是用户定义的.<img src="boat.gif" alt="Big Bo ...
- maven 项目配置
创建java web的maven项目方法有两种,一是先创建maven项目,再选择jdk 和 dynamic web 运行环境 ,二是创建java项目,然后转化为maven项目 1.将普通java项目转 ...
- Thank you for your resubmission. Performance - 2.3.10 We noticed that your app or its metadata includes irrelevant third-party platform information. Specifically, Android logo is mentioned in the
被拒很多次,各种修改,最后发现是提交的时候,含有安卓的图标!欲哭无泪呀! Thank you for your resubmission. Performance - 2.3.10 We notice ...
- ubutu之jdk安装
1.jdk下载 http://www.oracle.com/technetwork/java/javase/downloads/jdk8-downloads-2133151.html 2.解压jdk- ...
- js 区分数据类型
这是第二版,可以区分 1.基本数据类型(string.number.boolean) undefined.null 2.引用类型 数组.RegExp.函数. 自定义数据类型(通过new 函数名得到) ...