最近遇到个问题,挺有意思。我在给APP集成SDK进行网络请求的时候,报了一个错。
错误截图
Task <8D0840BE-B5A9-49C1-897C-A7783B50D106>.<13> finished with error [-1022] Error Domain=NSURLErrorDomain Code=-1022 "The resource could not be loaded because the App Transport Security policy requires the use of a secure connection." UserInfo={NSLocalizedDescription=The resource could not be loaded because the App Transport Security policy requires the use of a secure connection.
我一看,简单啊!info.plist麻利的就加上ATS,白名单过滤也加上了,错误依旧还在。
于是代码打印了一下读取到info.plist文件的数据,发觉添加的设置并没有被系统读取到。
NSBundle *bundle = [NSBundle mainBundle];
NSString *path = [bundle pathForResource:@"Info" ofType:@"plist"];
NSDictionary *dict = [NSDictionary dictionaryWithContentsOfFile:path];
NSLog(@"%@", dict);
最后是通过在下面的位置进行设置ATS解决的问题
XCode设置Info.plist
通常情况下,info.plist和这里是同步的,可能这个工程在生成的时候他俩的关联被断开了(其实是不晓得这俩之间的具体关系),但是系统最终读取的配置数据是以这里为准的。
另外,提个调试过程中有意思的点。
在确定项目的http网络是否通畅的时候,我第一次采用的是UIWebView.代码如下:
self.webView = [[UIWebView alloc]initWithFrame:self.view.bounds];
[self.webView loadRequest:[NSURLRequest requestWithURL:[NSURL URLWithString:@"https://www.baidu.com"]]];
[self.view addSubview:self.webView];
第一次我访问的地址是https://www.baidu.com,页面如期加载出来了,第二次我访问的地址是http://www.baidu.com,页面依旧如期加载出来了。我得出结论:http网络访问通畅。
后来我换了一种方式,代码如下:
NSURL *url = [NSURL URLWithString:@"http://www.baidu.com"];
NSURLSession *session = [NSURLSession sharedSession];
NSURLSessionDataTask *firsttask = [session dataTaskWithURL:url completionHandler:^(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error) {
NSLog(@"load finished");
}];
[firsttask resume];
第一次我访问的地址是https://www.baidu.com,请求执行无错,第二次我访问的地址是http://www.baidu.com,请求执行得到返回:http请求被拦截。我得出结论:http网络访问不通畅。
http请求返回Error,ATS被拦截
两个结论是冲突的。
然后我想到会不会是UIWebView缓存了之前请求结果,所以我把APP卸载了,重新再用WebView的代码请求http://www.baidu.com,结果没有加载出来。
结论:http网络不通畅,UIWebView在无网络的情况下会缓存同域名的https的请求结果来显示http请求。有兴趣,可以尝试下
我曾执笔雕刻时光 奈何良辰难书过往