您的位置:首页 > 其它

NSURLSession和NSURLConnection比较

2015-09-25 20:16 253 查看
背景介绍:

作为Core Foundation / CFNetwork 框架的APIs之上的一个抽象,NSURLConnection伴随着2003年Safari浏览器的原始发行版本,诞生于10年前。NSURLConnection这个名字,实际上指的是一组构成Foundation框架中URL加载系统的相互关联的组件:NSURLRequest,NSURLResponse,NSURLProtocol,NSURLCache,NSHTTPCookieStorage,NSURLCredentialStorage,以及和它同名的NSURLConnection。

在2013年的WWDC上,Apple揭开了NSURLConnection继任者的面纱:NSURLSession。

与NSURLConnection类似,除了同名类NSURLSession,NSURLSession也是指一组相互依赖的类。NSURLSession包括与之前相同的组件,例如NSURLRequest, NSURLCache等。NSURLSession的不同之处在于,它把 NSURLConnection替换为NSURLSession, NSURLSessionConfiguration,以及3个NSURLSessionTask的子类:NSURLSessionDataTask, NSURLSessionUploadTask,
和NSURLSessionDownloadTask。

NSURLSession相对于NSConnection来说,有很多优势。
1、后台上传和下载
2、可以暂停和重启网络操作

3、可以对缓存策略,session类型、任务类型(比如上传、下载等任务)进行单独的配置

4、更多更丰富的代理模式

具体实现:

分别用NSURLSession和NSConnection实现请求

在ViewController.m中添加如下代码

- (void)requestWithConnection
{
NSString *londonWeatherUrl =
@"http://api.openweathermap.org/data/2.5/weather?q=London,uk";
NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString:londonWeatherUrl]];

[NSURLConnection sendAsynchronousRequest:request
queue:[NSOperationQueue mainQueue]
completionHandler:^(NSURLResponse *response,
NSData *data,
NSError *error){
//处理返回的数据data
//1. 将data转换为JSON
//2. 打印内容
NSDictionary *dictionary = [NSJSONSerialization
JSONObjectWithData:data
options:NSJSONReadingMutableContainers
error:nil];

for (NSString *str in dictionary.allKeys) {
NSLog(@"%@:%@", str, dictionary[str]);
}
}];
}

- (void)requestWithSession
{
NSString *londonWeatherUrl =
@"http://api.openweathermap.org/data/2.5/weather?q=London,uk";

NSURLSession *session = [NSURLSession sharedSession];
NSURLSessionDataTask *task =
[session dataTaskWithURL:[NSURL URLWithString:londonWeatherUrl]
completionHandler:^(NSData *data,
NSURLResponse *response,
NSError *error){
//处理数据
NSDictionary *dictionary = [NSJSONSerialization
JSONObjectWithData:data
options:NSJSONReadingMutableContainers
error:nil];

for (NSString *str in dictionary.allKeys) {
NSLog(@"%@:%@", str, dictionary[str]);
}
}];
[task resume];
}


- (void)viewDidLoad {
[super viewDidLoad];

[self requestWithConnection];
//[self requestWithSession];
}
1、分别注释掉一行代码来查看结果,由于他们是进行异步请求的,所以如果同时执行的话,结果会比较混乱。

2015-09-25 19:41:46.482 NetworkProgrammingTest[980:50010] base:stations
2015-09-25 19:41:46.482 NetworkProgrammingTest[980:50010] id:2643743
2015-09-25 19:41:46.483 NetworkProgrammingTest[980:50010] dt:1443179989
2015-09-25 19:41:46.483 NetworkProgrammingTest[980:50010] main:{
humidity = 58;
pressure = 1023;
temp = "288.56";
"temp_max" = "291.48";
"temp_min" = "287.15";
}
2015-09-25 19:41:46.483 NetworkProgrammingTest[980:50010] coord:{
lat = "51.51";
lon = "-0.13";
}
2015-09-25 19:41:46.483 NetworkProgrammingTest[980:50010] wind:{
deg = 300;
speed = "2.6";
}
2015-09-25 19:41:46.484 NetworkProgrammingTest[980:50010] sys:{
country = GB;
id = 5093;
message = "0.022";
sunrise = 1443160292;
sunset = 1443203507;
type = 1;
}
2015-09-25 19:41:46.484 NetworkProgrammingTest[980:50010] weather:(
{
description = "scattered clouds";
icon = 03d;
id = 802;
main = Clouds;
}
)
2015-09-25 19:41:46.484 NetworkProgrammingTest[980:50010] visibility:10000
2015-09-25 19:41:46.484 NetworkProgrammingTest[980:50010] clouds:{
all = 40;
}
2015-09-25 19:41:46.484 NetworkProgrammingTest[980:50010] cod:200
2015-09-25 19:41:46.487 NetworkProgrammingTest[980:50010] name:London
和以下返回的JSON内容是相同的,说明请求成功

{"coord":{"lon":-0.13,"lat":51.51},"weather":[{"id":802,"main":"Clouds","description":"scattered clouds","icon":"03d"}],"base":"stations","main":{"temp":289.1,"pressure":1023,"humidity":51,"temp_min":287.15,"temp_max":291.48},"visibility":10000,"wind":{"speed":3.6,"deg":300},"clouds":{"all":40},"dt":1443183793,"sys":{"type":1,"id":5091,"message":0.0149,"country":"GB","sunrise":1443160296,"sunset":1443203501},"id":2643743,"name":"London","cod":200}


2、用NSURLSession比较容易遗忘的就是[task resume]。如果没有这个代码,task就不会执行,就无法请求到数据。

备注:

我之前刚入门的时候一直不知道completionHandler:^(NSData *data, NSResponse *response, NSError *error)

中间的参数是何时何地传入的。

我的理解是,当执行请求request后,你所请求的服务器会返回一个数据。

也就是请求结束后,cocoa会帮你调用completionHandler中的block。而data就是请求返回的数据。

(作为新手,你并不需要知道它使如何调用的,只要在没有error的情况下,你就可以直接处理data,来获取你想要的数据)。

参考网站:
http://jishu.zol.com.cn/201091.html http://www.raywenderlich.com/51127/nsurlsession-tutorial
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: