用多了AFN难免对苹果底层的网络请求陌生了许多,编程所谓一天不敲就手生,尝试几种原生网络请求方法,和大家共享…
普及:
URL Session的基本概念
1.三种工作模式:
默认会话模式(default):工作模式类似于原来的NSURLConnection,使用的是基于磁盘缓存的持久化策略,使用用户keychain中保存的证书进行认证授权。
瞬时会话模式(ephemeral):该模式不使用磁盘保存任何数据。所有和会话相关的caches,证书,cookies等都被保存在RAM中,因此当程序使会话无效,这些缓存的数据就会被自动清空。
后台会话模式(background):该模式在后台完成上传和下载,在创建Configuration对象的时候需要提供一个NSString类型的ID用于标识完成工作的后台会话。
2.NSURLSession支持的三种任务
NSURLSession类支持三种类型的任务:加载数据,下载和上传。
二、相关的类
NSURLConnection这个名字,实际上指的是一组构成Foundation框架中URL加载系统的相互关联的组件:NSURLRequest,NSURLResponse,NSURLProtocol,NSURLCache,NSHTTPCookieStorage,NSURLCredentialStorage,以及和它同名的NSURLConnection。
在WWDC 2013中,Apple的团队对NSURLConnection进行了重构,并推出了NSURLSession作为替代。
NSURLSession也是一组相互依赖的类,它的大部分组件和NSURLConnection中的组件相同如NSURLRequest,NSURLCache等。而NSURLSession的不同之处在于,它将NSURLConnection替换为NSURLSession和NSURLSessionConfiguration,以及3个NSURLSessionTask的子类:NSURLSessionDataTask, NSURLSessionUploadTask, 和NSURLSessionDownloadTask。
使用:
GET:
block 方式:
-(void)networking1{
_MB = [MBProgressHUD showHUDAddedTo:self.navigationController.view animated:YES];
[_MB setLabelText:@"正在加载..."];
[_MB show:YES];
NSString *path = @"http://apis.juhe.cn/train/ticket.price.php";
NSString *URL = [NSString stringWithFormat:@"%@?key=%@&train_no=%@&from_station_no=%@&to_station_no=%@&date=%@",path,@"718ab93527120b628c21db1958d9af1",train_no,from_station_no,to_station_no,self.dateStr];
//以免有中文进行UTF编码
NSString *UTFPathURL = [URL stringByAddingPercentEncodingWithAllowedCharacters:[NSCharacterSet URLQueryAllowedCharacterSet]];
//请求路径
NSURL *url = [NSURL URLWithString:UTFPathURL];
//创建请求对象
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
//设置请求超时
request.timeoutInterval = 2;
//创建session配置对象
NSURLSessionConfiguration *configuration = [NSURLSessionConfiguration defaultSessionConfiguration];
//创建session对象
NSURLSession *session = [NSURLSession sessionWithConfiguration:configuration];
//添加网络任务
NSURLSessionTask *task = [session dataTaskWithRequest:request completionHandler:^(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error) {
NSLog(@"网络请求开始->");
if (error) {
NSLog(@"请求失败...");
dispatch_async(dispatch_get_main_queue(), ^{
[_MB hide:YES];
});
}else{
dispatch_async(dispatch_get_main_queue(), ^{
[_MB hide:YES];
});
NSLog(@"请求成功:%@",[[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding]);
//用苹果字典JSON解析(NSJSONSerialization) 解析JSON
NSDictionary *dataDict = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:nil];
NSLog(@"解析JSON完毕:打印下看看%@",dataDict);
NSNull *result = [dataDict objectForKey:@"result"];
if (result == [NSNull null]) {
UIAlertController *av = [UIAlertController alertControllerWithTitle:@"提示" message:@"网络错误,请重试" preferredStyle:UIAlertControllerStyleAlert];
[av addAction:[UIAlertAction actionWithTitle:@"OK" style:UIAlertActionStyleDefault handler:nil]];
[self presentViewController:av animated:YES completion:nil];
}else{
NSDictionary *resultDict = (NSDictionary *)result;
NSLog(@"请求成功数据已经,继续展示到界面中:%@",resultDict);
}
}
}];
//开始任务
[task resume];
}