网络之数据请求(2)
2016-05-06 本文已影响13人
永恒守护__刘鹏辉
NSURLSession
- 在WWDC 2013中,Apple的团队对NSURLConnection进行了重构,并推出了NSURLSession作为替代
- 支持后台运行的网络任务
- 暂停、停止、重启网络任务,不再需要NSOpation封装
- 请求可以使用同样的配置容器
- 不同的session可以使用不同的私有存储,block和代理可以同时起作用
- 直接从文件系统上传、下载
- 为了方便程序员使用,苹果提供了一个全局session
- 所有的任务(task)都是由Session发起的
- 所有的任务默认是挂起的,需要Resume
NSURLSession的工作模式
- 默认会话模式(default)
- 瞬时会话模式(ephemeral)
- 后台会话模式(background)
NSURLSession支持的任务
- 加载数据、下载、上传
-----------------------ViewController.m----------------------
#import "ViewController.h"
@interface ViewController ()<NSURLSessionDataDelegate>
// 保存网络请求的结果
@property (nonatomic, strong) NSMutableData *resultData;
@end
@implementation ViewController
- (void)viewDidLoad {
[super viewDidLoad];
}
- (IBAction)buttonClicked:(id)sender
{
// [self requestData1];
// [self requestData2];
// [self requestData3];
[self requestData4];
}
#pragma mark -------------------------get异步 代理模式-------------------------------
- (void)requestData1
{
// NSURLSession 代理人的属性是只读的
// 参数一 : 会话模式
// 参数二 : 代理人
// 参数三 : 代理方法在哪个线程中进行
NSURLSession *session = [NSURLSession sessionWithConfiguration:[NSURLSessionConfiguration defaultSessionConfiguration] delegate:self delegateQueue:[NSOperationQueue mainQueue]];
NSURL *url = [NSURL URLWithString:@"http://ipad-bjwb.bjd.com.cn/DigitalPublication/publish/Handler/APINewsList.ashx?date=20131129&startRecord=1&len=5&udid=1234567890&terminalType=Iphone&cid=213"];
// NSURLSessionTask的子类对象
NSURLSessionDataTask *task = [session dataTaskWithURL:url];
[task resume];
}
#pragma mark ---------------------------get异步 block模式------------------------------
- (void)requestData2
{
// 使用系统提供的全局的NSURLSession对象, 是一个单例
NSURLSession *session = [NSURLSession sharedSession];
NSString *urlString = @"http://ipad-bjwb.bjd.com.cn/DigitalPublication/publish/Handler/APINewsList.ashx?date=20131129&startRecord=1&len=5&udid=1234567890&terminalType=Iphone&cid=213";
NSURL *url = [NSURL URLWithString:urlString];
//NSURLSession是基于任务的, 所以所有的东西都要放到任务里面, NSURLSessionTask就是NSURLSession的执行对象
NSURLSessionTask *task = [session dataTaskWithURL:url completionHandler:^(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error)
{
if (error == nil)
{
NSLog(@"data ==== %@", data);
NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingAllowFragments error:nil];
NSLog(@"dic ==== %@", dic);
}
}];
// NSURLSession的所有的任务默认是挂起的, 所以一定要调用resume方法, 让任务开始
[task resume];
}
#pragma mark ---------------------------post异步 代理模式-----------------------------
- (void)requestData3
{
NSURLSession *session = [NSURLSession sessionWithConfiguration:[NSURLSessionConfiguration defaultSessionConfiguration] delegate:self delegateQueue:[NSOperationQueue mainQueue]];
NSURL *url = [NSURL URLWithString:@"http://ipad-bjwb.bjd.com.cn/DigitalPublication/publish/Handler/APINewsList.ashx"];
NSString *string = @"date=20131129&startRecord=1&len=5&udid=1234567890&terminalType=Iphone&cid=213";
NSData *newData = [string dataUsingEncoding:NSUTF8StringEncoding];
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
[request setHTTPBody:newData];
[request setHTTPMethod:@"POST"];
NSURLSessionDataTask *dataTask = [session dataTaskWithRequest:request];
[dataTask resume];
}
#pragma mark ---------------------------post异步 block模式-------------------------
- (void)requestData4
{
NSURLSession *session = [NSURLSession sharedSession];
NSString *urlString = @"http://ipad-bjwb.bjd.com.cn/DigitalPublication/publish/Handler/APINewsList.ashx";
NSURL *url = [NSURL URLWithString:urlString];
NSMutableURLRequest *urlRequest = [NSMutableURLRequest requestWithURL:url];
NSString *dataString = @"date=20131129&startRecord=1&len=5&udid=1234567890&terminalType=Iphone&cid=213";
NSData *postData = [dataString dataUsingEncoding:NSUTF8StringEncoding];
[urlRequest setHTTPMethod:@"POST"];
[urlRequest setHTTPBody:postData];
NSURLSessionTask *task = [session dataTaskWithRequest:urlRequest completionHandler:^(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error)
{
if (error == nil)
{
NSLog(@"data ==== %@", data);
NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingAllowFragments error:nil];
NSLog(@"dic ==== %@", dic);
}
}];
[task resume];
}
#pragma mark ---------------------NSURLSessionDataDelegate协议方法--------------------
// 服务器开始响应
- (void)URLSession:(NSURLSession *)session dataTask:(NSURLSessionDataTask *)dataTask didReceiveResponse:(NSURLResponse *)response completionHandler:(void (^)(NSURLSessionResponseDisposition))completionHandler
{
// NSURLSession的代理协议里面 必须设置允许继续请求, 才会继续响应服务器
completionHandler(NSURLSessionResponseAllow);
self.resultData = [NSMutableData data];
}
// 接收到数据
- (void)URLSession:(NSURLSession *)session dataTask:(NSURLSessionDataTask *)dataTask didReceiveData:(NSData *)data
{
[self.resultData appendData:data];
}
// 结束响应
- (void)URLSession:(NSURLSession *)session task:(NSURLSessionTask *)task didCompleteWithError:(NSError *)error
{
if (error == nil)
{
NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:self.resultData options:NSJSONReadingAllowFragments error:nil];
NSLog(@"data ==== %@", self.resultData);
NSLog(@"dic === %@", dic);
}
}
- (void)didReceiveMemoryWarning {
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
@end