最直接的办法就是使用NSURLSession和系统提供的代理去请求资源。使用这个方法,我们只需在程序中提供两块儿代码:
- 创建配置对象以及基于该配置对象的session代码
- 在数据接收完成之后的一个completion handler
使用系统提供的代理,只需要为每个请求写一行代码就可以获取指定的URL,具体代码如下:
/// Objective-C
NSURLSession *sys_delegate_session = [NSURLSession sessionWithConfiguration:default_config];
NSURL *url = [NSURL URLWithString:@"https://www.example.com/"];
[[sys_delegate_session dataTaskWithURL:url completionHandler:^(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error) {
NSLog(@"Got response %@ with error %@.\n", response, error);
NSLog(@"DATA:\n%@\nEND DATA\n", [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding]);
}] resume];
/// Swift
let sys_delegate_session = URLSession(configuration: default_config)
guard let url:URL = URL(string: "https://www.example.com/") else{
return
}
(sys_delegate_session.dataTask(with: url) { (data, response, error) in
if let error = error {
print("Error: \(error)")
} else if let response = response,
let data = data,
let string = String(data: data, encoding: .utf8) {
print("Response: \(response)")
print("DATA:\n\(string)\nEND DATA\n")
}
}).resume()
这里和上一节创建的session不同之处在于,不需要我们自己去指定delegate对象了,而是直接使用的方法sessionWithConfiguration:
来创建的session。
这里要说明一下,completion handler和delegate是不能同时调用的(起作用)