NSURLSessionConfiguration的三种类型:
- A default session behaves much like the shared session, but allows more configuration, and allows you to obtain data incrementally with a delegate.
- Ephemeral sessions are similar to shared sessions, but don’t write caches, cookies, or credentials to disk.
- Background sessions let you perform uploads and downloads of content in the background while your app isn't running.
1、 defaultSessionConfiguration
: 默认的session配置, 类似NSURLConnection的标准配置, 使用硬盘来存储缓存数据.
2、 ephemeralSessionConfiguration
: 临时的session配置, 与默认配置相比, 这个配置不会将缓存、cookie等存在本地,只会存在内存里,所以当程序退出时,所有的数据都会消失
3、 backgroundSessionConfiguration
: 后台session配置, 与默认配置类似, 不同的是会在后台开启另一个线程来处理网络数据.
回调方式二选一(Block)或 (Delegate):
使用NSURLSession,拢共分两步:
- 第一步 通过NSURLSession的实例创建task
- 第二部 执行task
简单GET请求
// 快捷方式获得session对象
NSURLSession *session = [NSURLSession sharedSession];
NSURL *url = [NSURL URLWithString:@"http://www.daka.com/login?username=daka&pwd=123"];
// 通过URL初始化task,在block内部可以直接对返回的数据进行处理
NSURLSessionTask *task = [session dataTaskWithURL:url
completionHandler:^(NSData *data, NSURLResponse *response, NSError error) {
NSLog(@"%@", [NSJSONSerialization JSONObjectWithData:data options:kNilOptions error:nil]);
}];
// 启动任务
[task resume];
简单POST请求
NSURL *url = [NSURL URLWithString:@"http://www.daka.com/login"];
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
request.HTTPMethod = @"POST";
request.HTTPBody = [@"username=daka&pwd=123" dataUsingEncoding:NSUTF8StringEncoding];
NSURLSession *session = [NSURLSession sharedSession];
// 由于要先对request先行处理,我们通过request初始化task
NSURLSessionTask *task = [session dataTaskWithRequest:request
completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) { NSLog(@"%@", [NSJSONSerialization JSONObjectWithData:data options:kNilOptions error:nil]); }];
[task resume];