#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. json的中括号和大括号的使用?

    参考这篇文章: http://www.cnblogs.com/sgdkg/archive/2012/12/03/2799723.html json 变量有两种可能, 可能是一个对象, (类似 类的实例 ...

  2. 如何在editplus中配置ctags?

    首先要说明的是, 在editPlus中的ctags功能确实是没有 vs vim等中的好用. 最主要的原因 是它不能直接在文件中 跳转. 而是要通过一个另外的框来实现, 这就大大的降低了跳转的速度和使用 ...

  3. [整理]VS2013常用插件

    VS2013常用插件 (工欲善其事,必先利其器.VS2013全攻略(技巧,快捷键,插件)[http://developer.51cto.com/art/201404/437282_all.htm] 代 ...

  4. winform 开发心得~

    winform自适应不同分辨率 不同dpi 1.窗体AutoScaleMode属性 使用None 2.自定义控件 AutoScaleMode 使用Inherit 3.所有控件窗体字体使用px为单位

  5. 使用ajax获取JSON数据的jQuery代码的格式

    具体的也可以参考:http://www.w3cfuns.com/notes/16039/2b004b1bcdf79092f2e66b2bbe9f51df.html

  6. Swift2.1 语法指南——类型转换

    原档:https://developer.apple.com/library/prerelease/ios/documentation/Swift/Conceptual/Swift_Programmi ...

  7. Android开发学习笔记--计时器的应用实例

    为了了解安卓计时器的用法,写了一个秒表的应用,正是这个秒表,让我对Android应用的速度大跌眼镜,我设置了一个计时器,10ms更新一次显示的时间,然后更标准的时间一比较发现,跑10s就有一秒的时间误 ...

  8. BZOJ4034——[HAOI2015]T2

    1.题目大意:用一个数据结构支持树的点修改和子树修改.树上路径和 2.分析:树链剖分裸题 #include <cstdio> #include <cstdlib> #inclu ...

  9. ionic中返回上一页

    .controller('NewsCtrl', ["$scope", "$ionicHistory", "$http","$tim ...

  10. web.xml 模板和Servlet版本

    最近没事干,写自己小项目(项目周期无限长.开发效率无限低)的时候,遇到web.xml的dtd声明不正确,这里罗列下从Eclipse里新建项目时,自动生成的web.xml,供以后遇到类似问题的时候进行参 ...