[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(30, 500, 80, 40)];
    sessionPostButton.backgroundColor=[UIColor orangeColor];
    [sessionPostButton setTitle:@"Session" forState:UIControlStateNormal];
    [sessionPostButton addTarget:self action:@selector(sessionPostData) forControlEvents:UIControlEventTouchUpInside];
    
    sessionDelegatePostButton=[[UIButton alloc]initWithFrame:CGRectMake(210, 500, 80, 40)];
    sessionDelegatePostButton.backgroundColor=[UIColor orangeColor];
    [sessionDelegatePostButton setTitle:@"Delegate" forState:UIControlStateNormal];
    [sessionDelegatePostButton addTarget:self action:@selector(sessionDelegatePostData) forControlEvents:UIControlEventTouchUpInside];
    
    table=[[UITableView alloc]initWithFrame:CGRectMake(0, 20, 320, 568-20) 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:0 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];
}

 

posted @ 2015-12-16 13:03  death3721  阅读(330)  评论(0编辑  收藏  举报