当我将 Xcode 更新到 7.0 或 iOS 9.0 时,我遇到了这个问题。不知何故,它开始给我标题错误
“无法加载资源,因为应用程序传输安全策略需要使用安全连接”
网络服务方法:
-(void)ServiceCall:(NSString*)ServiceName :(NSString *)DataString { NSURLSessionConfiguration *sessionConfiguration = [NSURLSessionConfiguration defaultSessionConfiguration]; [sessionConfiguration setAllowsCellularAccess:YES]; [sessionConfiguration setHTTPAdditionalHeaders:@{ @"Accept" : @"application/json" }]; NSURLSession *session = [NSURLSession sessionWithConfiguration:sessionConfiguration]; NSURL *url = [NSURL URLWithString:[NSString stringWithFormat:@"%@",ServiceURL]]; NSLog(@"URl %@%@",url,DataString); // Configure the Request NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url]; [request setValue:[NSString stringWithFormat:@"%@=%@", strSessName, strSessVal] forHTTPHeaderField:@"Cookie"]; request.HTTPBody = [DataString dataUsingEncoding:NSUTF8StringEncoding]; request.HTTPMethod = @"Post"; // post the request and handle response NSURLSessionDataTask *postDataTask = [session dataTaskWithRequest:request completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) { // Handle the Response if(error) { NSLog(@"%@",[NSString stringWithFormat:@"Connection failed: %@", [error description]]); // Update the View dispatch_async(dispatch_get_main_queue(), ^{ // Hide the Loader [MBProgressHUD hideHUDForView:[[UIApplication sharedApplication] delegate].window animated:YES]; }); return; } NSArray * cookies = [[NSHTTPCookieStorage sharedHTTPCookieStorage] cookiesForURL:request.URL]; for (NSHTTPCookie * cookie in cookies) { NSLog(@"%@=%@", cookie.name, cookie.value); strSessName=cookie.name; strSessVal=cookie.value; } NSString *retVal = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding]; }]; [postDataTask resume]; }
该服务对于 Xcode 早期版本和 iOS 早期版本运行良好但是当我更新到 iOS 9.0 上的 Xcode 7.0 时,当我调用上述 Web 服务方法时,它开始给我以下问题。我得到的记录错误是:
连接失败:错误域 = NSURLErrorDomain 代码 = -1022 “无法加载资源,因为应用程序传输安全策略需要使用安全连接。” UserInfo={NSUnderlyingError=0x7fada0f31880 {Error Domain=kCFErrorDomainCFNetwork Code=-1022 “(null)”}, NSErrorFailingURLStringKey= MyServiceURL , NSErrorFailingURLKey= MyServiceURL , NSLocalizedDescription=资源无法加载,因为应用传输安全策略需要使用安全的联系。}
我已经通过在 info.plist 中添加一些键来解决它。我遵循的步骤是:
打开我的项目目标info.plist文件
info.plist
NSAppTransportSecurity添加了一个名为Dictionary.
NSAppTransportSecurity
Dictionary
添加了一个名为NSAllowsArbitraryLoadsas的子Boolean键并将其值设置YES为如下图所示。
NSAllowsArbitraryLoads
Boolean
YES
清理项目,现在一切都像以前一样运行良好。
编辑: 或者在info.plist文件的源代码中我们可以添加:
<key>NSAppTransportSecurity</key> <dict> <key>NSAllowsArbitraryLoads</key> <true/> <key>NSExceptionDomains</key> <dict> <key>yourdomain.com</key> <dict> <key>NSIncludesSubdomains</key> <true/> <key>NSThirdPartyExceptionRequiresForwardSecrecy</key> <false/> </dict> </dict> </dict>