#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方式获取网络数据并把数据显示到表格的更多相关文章

  1. [NSURLConnection]分别用Post和Get方式获取网络数据并把数据显示到表格

    @interface ViewController ()<UITableViewDataSource,UITableViewDelegate> { UIButton* getButton; ...

  2. Http方式获取网络数据

    通过以下代码可以根据网址获取网页的html数据,安卓中获取网络数据的时候会用到,而且会用Java中的sax方式解析获取到数据.(sax解析主要是解析xml)具体代码如下: package com.wy ...

  3. 用 get 同步/异步 方式获取网络数据并输出

    //同步请求 //创建NSString用来存储请求的网址 NSString* str=@"http://v.juhe.cn/weather/index?format=2&cityna ...

  4. android—获取网络数据

    取网络数据主要靠发交易(或者说请求,接口等),而这些交易由java中的网络通信,HttpURLConnection和HttpClient实现,以下是具体例子.   大家都知道,网络通信,发送请求有两种 ...

  5. 使用NSURLSession获取网络数据和下载文件

    使用NSURLSession获取网络数据 使用NSURLSession下载文件

  6. 使用promise方式来获取网络数据

    获取网络数据 let data = []; new Promise(function(resolve,reject){ axios.post('api.php').then(function(resp ...

  7. Swift - 异步获取网络数据封装类

    使用NSURLConnection.sendAsynchronousRequest()可以采用异步获取的方式取得数据.下面通过对数据获取类进行封装,演示如何进行数据请求与接收. 1,HttpContr ...

  8. Windows Phone 同步方式获取网络类型

    原文:Windows Phone 同步方式获取网络类型 在Windows Phone 开发中有时候需要获取设备当前连接网络的类型,是Wifi,还是2G,3G,或者4G,SDK中提供获取网络类型的API ...

  9. Android简易实战教程--第四十七话《使用OKhttp回调方式获取网络信息》

    在之前的小案例中写过一篇使用HttpUrlConnection获取网络数据的例子.在OKhttp盛行的时代,当然要学会怎么使用它,本篇就对其基本使用做一个介绍,然后再使用它的接口回调的方式获取相同的数 ...

随机推荐

  1. php的exit和die

    首先, 两者是相等的: exit is equivalent to die; 其次, 都是语言构造器, language construct. 不是函数! 后面的内容用括号括起来只是为了方便... 用 ...

  2. linux下vim如何配置markdown插件

    在vim中设置markdown语法高亮是一个不错的选择,但是在google中搜索到的很多都是比较老的设置方式,甚至vim插件下载页面都是一个旧的版本.这里总结下我的修改过程,以帮助像我一样纠结的人. ...

  3. jquery点击label触发2次的问题

    今天写问卷的时候遇到个label点击的时候,监听的click事件被执行两次:产生这个的原因么...事件冒泡 <div class="questionBox checkBox" ...

  4. Maven初级学习(二)Maven使用入门

    序,学习配置pom.xml,利用maven生成eclipes项目. 一.编写POM POM Project Obejct Model,项目对象模型. 编写pom.xml,新建文件夹hello-worl ...

  5. mongodb_修改器($inc/$set/$unset/$push/$pop/upsert......)

    主从复制:http://blog.csdn.net/drifterj/article/details/7833883 对于文档的更新除替换外,针对某个或多个文档只需要部分更新可使用原子的更新修改器,能 ...

  6. Javascript实现AutoComplete自动匹配功能

    功能分析: 避免客户端频繁的访问服务器,因此客户端需要一个timer,监听键盘按键间隔时间,300-600毫秒能够接受. 服务端对要查找的数据源如果不大的话,应该尽量缓存在服务端内存中,而不是每次查找 ...

  7. PHP 如何显示大数字,防止显示为 科学计数法 形式

    PHP 数字超过一定长度时,会自动转换为 科学计数法 的形式,如 1.2345678912346E+16: 如何 避免转换,让它原样展示呢? 不过,可以用PHP函数 number_format() 来 ...

  8. Ubuntu 14 修改默认打开方式

    通过研究,有三种修改方式. 方式一: 修改路径:右上角“系统设置” -> 详细信息 -> 默认应用程序 但是,有个缺陷,可修改的项比较少. 方式二: 例如,修改pdf的打开方式,只要查看任 ...

  9. Sql统计一个字符串在另一个字符串出现的次数的函数-fnQueryCharCountFromString

    SET ANSI_NULLS ON GO SET QUOTED_IDENTIFIER ON GO ),)) returns int as begin declare @pos int,@n int , ...

  10. linux安装包地址备忘

    64位系统安装包: http://mirrors.163.com/centos/5/os/x86_64/CentOS/ 32位系统安装包: http://mirrors.163.com/centos/ ...