[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盛行的时代,当然要学会怎么使用它,本篇就对其基本使用做一个介绍,然后再使用它的接口回调的方式获取相同的数 ...
随机推荐
- php的exit和die
首先, 两者是相等的: exit is equivalent to die; 其次, 都是语言构造器, language construct. 不是函数! 后面的内容用括号括起来只是为了方便... 用 ...
- CRect类
类CRect是对Windows结构RECT的封装,凡是能用RECT结构的地方都可以用CRect代替. 结构RECT表示一个矩形的位置和尺寸,其定义为: typedef struct tagRECT{ ...
- Javascript设计模式详解
Javascript常用的设计模式详解 阅读目录 一:理解工厂模式 二:理解单体模式 三:理解模块模式 四:理解代理模式 五:理解职责链模式 六:命令模式的理解: 七:模板方法模式 八:理解javas ...
- HTML中head头结构
HTML head 头部分的标签.元素有很多,涉及到浏览器对网页的渲染,SEO等等,而各个浏览器内核以及各个国内浏览器厂商都有些自己的标签元素,这就造成了很多差异性.移动互联网时代,head 头部结构 ...
- Jquery实现滚动显示欢迎字幕效果
Jquery控制滚动显示欢迎字幕: 参考代码: <!DOCTYPE html> <html> <head> <title>Colin Marquee W ...
- 如何利用cookie来保存用户登录账号
众所周知,cookie在网页编写中不接或缺,今天就谈谈如何利用cookie技术来保存用户登录账号 1.首先是否保存用户登录账号当然是用户自行决定,所以我们需要在用户登录界面设置一个复选框,以此取得用户 ...
- 微信公众平台中添加qq在线聊天代码
微信公众平台是个不错的媒体,可以和你的小伙伴们即时交流,但你的小伙伴们是用手机上的微信,打字自然就慢了:有人说用微信网页版,那个也不习惯,再说也不一定所有人都知道网页版微信.(2014.01.22更新 ...
- Mac Pro 修改主机名
修改 主机名称 sudo scutil --set HostName jianbao-PC 修改 共享名称 sudo scutil --set ComputerName jianbao-PC
- 第六天 做的app不会改变什么
app包括资源和功能,做完之后没有改变什么
- ASP.NET、C#调用外部可执行exe文件--多种方案
一. try { //方法一 //调用自己的exe传递参数 //Process proc = new Process(); //proc.StartInfo.FileName = @"D:\ ...