由于应用程序传输安全策略要求使用安全连接,因此无法加载资源。

605

我在将Xcode更新到7.0或iOS 9.0后遇到了问题。不知何故,它开始给我带来标题错误

"由于应用程序传输安全策略要求使用安全连接,因此无法加载资源"

Web服务方法:

- (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之前的版本中运行良好。但是当我升级到Xcode 7.0并运行在iOS 9.0上时,当我调用上述web服务方法时,它开始给我以下问题。我得到的记录错误是:
连接失败:错误域=NSURLErrorDomain Code=-1022 “由于应用程序传输安全策略要求使用安全连接,因此无法加载资源。” UserInfo={NSUnderlyingError=0x7fada0f31880 {Error Domain=kCFErrorDomainCFNetwork Code=-1022 “(null)”},NSErrorFailingURLStringKey=MyServiceURL,NSErrorFailingURLKey=MyServiceURL,NSLocalizedDescription=由于应用程序传输安全策略要求使用安全连接,因此无法加载资源。}
我尝试了以下问题和答案,但没有得到任何结果,还有什么高级想法可以消除该服务调用错误吗?
  1. iOS9中无法加载资源
  2. Xcode 7 beta 6的应用程序传输安全性
  3. https://dev59.com/01wY5IYBdhLWcg3wnYx3#32609970

可能是App Transport Security Xcode 7 beta 6的重复问题。 - AiOsN
25个回答

1095

我已经通过在info.plist文件中添加一些关键字来解决了这个问题。

  1. 打开我的项目目标的info.plist文件。

  2. 添加一个名为NSAppTransportSecurity的键作为Dictionary

  3. 添加一个名为NSAllowsArbitraryLoads的子键作为Boolean类型,并将其值设置为YES,就像下面的图片一样。

enter image description here

清理项目,现在一切都正常运行,就像以前一样。

参考链接:https://dev59.com/01wY5IYBdhLWcg3wnYx3#32609970

编辑:或者我们可以在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>

7
起初可能无法工作,你需要在“项目”>“目标”中添加密钥。 - orafaelreis
5
这是一些有用的苹果文档,链接如下:https://developer.apple.com/library/ios/documentation/General/Reference/InfoPlistKeyReference/Articles/CocoaKeys.html#//apple_ref/doc/uid/TP40009251-SW33。 - LargeGlasses
2
@MihirOza:没错,传输安全是iOS 9的一个新功能。 - Dominic K
2
如果您没有异常域,请删除NSExceptionDomains下的任何键。否则,它将成为NSAllowArbitraryLoads的异常,那么您必须使用https来访问此“exception”。 - DawnSong
8
对于Xcode 8.3 / Swift 3,分别是App Transport Security SettingsAllow Arbitrary Loads - Swapna Lekshmanan
显示剩余8条评论

331

请注意,在项目的 info.plist 中使用 NSAllowsArbitraryLoads = true 将允许所有与任何服务器的连接都不安全。如果你想确保只有一个特定域名可以通过不安全的连接访问,请尝试以下方法:

enter image description here

或者,作为源代码:

<key>NSAppTransportSecurity</key>
<dict>
    <key>NSExceptionDomains</key>
    <dict>
        <key>domain.com</key>
        <dict>
            <key>NSExceptionAllowsInsecureHTTPLoads</key>
            <true/>
            <key>NSIncludesSubdomains</key>
            <true/>
        </dict>
    </dict>
</dict>

编辑后请执行清理和构建项目操作。


谢谢你的回答,只是NSAllowArbitaryLoads对我没用,添加NSExceptionAllowsInsecureHTTPLoads就解决了问题。 - neeta
1
我还添加了这两个键:<!--包括允许HTTP请求--> <key>NSTemporaryExceptionAllowsInsecureHTTPLoads</key> <true/> <!--包括指定最小TLS版本--> <key>NSTemporaryExceptionMinimumTLSVersion</key> <string>TLSv1.1</string>它使加载速度快了很多。 - Sandy D.
1
注意:我现在正在使用XCode 8:如果您正在手动执行此操作,请确保右键单击域>值类型>字典以添加“..AllowsInsecure...”和“...IncludesSubdomains” - ArielSD
如果我在 domain.com 后面指定端口号,它就无法工作。(例如:domain.com:3001) - Shamsiddin Saidov

59

2
但是,这仍然不允许我对任何域名进行HTTP调用。有什么线索为什么会发生这种情况吗? - Mrug
即使是HTTP URL,URL也应该经过验证或具有有效的SSL证书。 - Teja Kumar Bethina

39

对于iOS 10.x和Swift 3.x [以下版本也支持],只需将以下行添加到'info.plist'中

<key>NSAppTransportSecurity</key>
<dict>
    <key>NSAllowsArbitraryLoads</key>
    <true/>
</dict>

1
对于10.x和Swift 3.x,我在其他地方看到的是键实际上是AppTransportSecurity和AllowsArbitraryLoads,但那是错误的。即使对于Swift 3.x,这些键仍然需要NS前缀。当我依赖于NS前缀来使用这些键时,错误消失了。 - Jazzmine

36

在Swift 4中,您可以使用以下步骤:

->前往 Info.plist

-> 点击信息属性列表的加号

-> 添加App Transport Security Settings作为字典

-> 点击加号图标 App Transport Security Settings

-> 添加Allow Arbitrary Loads并设置为 YES

如下图所示:

enter image description here


25

我已将其解决为plist文件。

添加NSAppTransportSecurity:字典。

添加名为“NSAllowsArbitraryLoads”的子键,布尔值为:YES

输入图像描述


21
这是苹果强制在您的API上实施更严格的安全性措施(强制使用HTTPS而不是HTTP)的方法。我将解释如何取消此安全设置。
在此处的大多数答案都指出需要将此键添加到您的info.plist中enter image description here。但是这并不能为我解决问题。我不得不将相同的键添加到内部Project -> Targets -> Info -> Custom iOS Target Properties {{enter image description here

这将允许任何人使用不安全的连接。但如果您只想允许特定域使用不安全的连接,可以在您的info.plist中添加以下内容。

enter image description here


谢谢,这对我有用!之前我只编辑了 plist 文件,但没有起作用。我很惊讶其他人是怎么做到的。 - jones

19

由于App Transport Security策略要求在Swift 4.03中使用安全连接,因此无法加载资源。

打开您的pList.info文件并将以下内容粘贴为源代码:

<key>NSAppTransportSecurity</key>
<dict>
    <key>NSAllowsArbitraryLoads</key>
    <true/>
</dict>

13

来自苹果文档

如果你正在开发一个新的应用程序,你应该完全使用HTTPS。如果你有一个现有的应用程序,你应该尽可能多地使用HTTPS,并制定一个尽快迁移其余部分的计划。此外,通过更高级别的API进行通信需要使用TLS 1.2版本加密并具备前向保密性。如果您尝试建立不符合此要求的连接,则会抛出错误。如果您的应用程序需要向不安全的域名发出请求,则必须在您的应用程序的Info.plist文件中指定此域名。

绕过应用程序传输安全性:

<key>NSAppTransportSecurity</key>
<dict>
  <key>NSExceptionDomains</key>
  <dict>
    <key>yourserver.com</key>
    <dict>
      <!--Include to allow subdomains-->
      <key>NSIncludesSubdomains</key>
      <true/>
      <!--Include to allow HTTP requests-->
      <key>NSTemporaryExceptionAllowsInsecureHTTPLoads</key>
      <true/>
      <!--Include to specify minimum TLS version-->
      <key>NSTemporaryExceptionMinimumTLSVersion</key>
      <string>TLSv1.1</string>
    </dict>
  </dict>
</dict>

允许所有不安全的域名

<key>NSAppTransportSecurity</key>
<dict>
  <!--Include to allow all connections (DANGER)-->
  <key>NSAllowsArbitraryLoads</key>
  <true/>
</dict>

阅读更多: 在iOS 9和OSX 10.11中配置应用程序传输安全例外


11
如果你正在使用Xcode 8.0和Swift 3.0或2.2

enter image description here


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接