#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. data and dream

    1 用通俗的语言介绍下线性回归->逻辑回归->SVM之间的区别和联系. 2 聚类算法的应用场景,以及k-means中的k值怎么确定. def center(data): center = ...

  2. [译]Mongoose指南 - Document

    更新 有几种方式更新document. 先看一下传统的更新方法 Tank.findById(id, function(err, tank){ if(err) return handleError(er ...

  3. Tomcat 部署详解

    前篇大概讲过了tomcat的发布和部署,以及测试. 本篇详细介绍下tomcat的部署相关的内容,本篇主要内容: 1 介绍下部署相关的内容,需要安装的文件以及上下文描述符 2 静态部署——在tomcat ...

  4. VTK初学一,a Mesh from vtkImageData—球冠

    #ifndef INITIAL_OPENGL #define INITIAL_OPENGL #include <vtkAutoInit.h> VTK_MODULE_INIT(vtkRend ...

  5. 【Solr】Solr的安装部署

    目录 Solr安装部署 Solr Web界面分析 回到顶部 solr安装和部署 solr下载 http://lucene.apache.org/ 安装solr,就是去部署它的war包,war包所在的位 ...

  6. Android应用如何监听自己是否被卸载及卸载反馈功能的实现

    一个应用被用户卸载肯定是有理由的,而开发者却未必能得知这一重要的理由,毕竟用户很少会主动反馈建议,多半就是用得不爽就卸,如果能在被卸载后获取到用户的一些反馈,那对开发者进一步改进应用是非常有利的.目前 ...

  7. IEnumerable<> ICollection <> IList<> 区别

    IEnumerable< ICollection < IList区别 public interface IEnumerable { IEnumerator GetEnumerator(); ...

  8. 【bzoj3631】[JLOI2014]松鼠的新家

    题目描述 松鼠的新家是一棵树,前几天刚刚装修了新家,新家有n个房间,并且有n-1根树枝连接,每个房间都可以相互到达,且俩个房间之间的路线都是唯一的.天哪,他居然真的住在"树"上.松 ...

  9. java之Date

    1.java时间处理 package com.bmkit.util.date; import java.text.DateFormat; import java.text.ParseException ...

  10. PHP Socket实现websocket(三)Stream函数

    除了socket函数也可以使用stream函数来实现服务器与客户端. 参考PHP 的Stream实现服务器客户端模型: http://php.net/manual/en/book.stream.php ...