ios 无法加载资源,因为应用传输安全策略要求使用安全连接

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/32631184/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-31 07:40:31  来源:igfitidea点击:

The resource could not be loaded because the App Transport Security policy requires the use of a secure connection

iosnsurlconnectionnsurlsessionios9xcode7

提问by Manab Kumar Mal

I am facing the Problem when I have updated my Xcode to 7.0 or iOS 9.0. Somehow it started giving me the Titled error

当我将 Xcode 更新到 7.0 或 iOS 9.0 时,我遇到了这个问题。不知何故它开始给我标题错误

"The resource could not be loaded because the App Transport Security policy requires the use of a secure connection"

“无法加载资源,因为应用传输安全策略要求使用安全连接”

Webservice Method:

网络服务方法:

-(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];

}

The service is Running fine for Xcode earlier versions and iOS previous versions But when I have updated to Xcode 7.0 that is on iOS 9.0, it started to give me the Problem like following when I am calling the above web service method. The Logged Error which I am getting is:

该服务对于 Xcode 早期版本和 iOS 早期版本运行良好但是当我更新到 iOS 9.0 上的 Xcode 7.0 时,当我调用上述 Web 服务方法时,它开始出现如下问题。我得到的记录错误是:

Connection failed: 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={NSUnderlyingError=0x7fada0f31880 {Error Domain=kCFErrorDomainCFNetwork Code=-1022 "(null)"}, NSErrorFailingURLStringKey=MyServiceURL, NSErrorFailingURLKey=MyServiceURL, NSLocalizedDescription=The resource could not be loaded because the App Transport Security policy requires the use of a secure connection.}

连接失败:错误域=NSURLErrorDomain 代码=-1022“无法加载资源,因为应用传输安全策略要求使用安全连接。” UserInfo={NSUnderlyingError=0x7fada0f31880 {Error Domain=kCFErrorDomainCFNetwork Code=-1022 "(null)"}, NSErrorFailingURLStringKey= MyServiceURL, NSErrorFailingURLKey= MyServiceURL, NSLocalizedDescription=无法加载资源,因为应用传输安全策略要求使用安全联系。}

I have tried Following Questions and answers but did not get any result there, is there any advance idea how I can remove that service call error?

我已经尝试了以下问题和答案,但没有得到任何结果,是否有任何关于如何消除该服务呼叫错误的预先想法?

  1. The resource could not be loaded is ios9
  2. App Transport Security Xcode 7 beta 6
  3. https://stackoverflow.com/a/32609970
  1. 资源无法加载是ios9
  2. 应用传输安全 Xcode 7 beta 6
  3. https://stackoverflow.com/a/32609970

回答by Manab Kumar Mal

I have solved it with adding some key in info.plist. The steps I followed are:

我已经通过在 info.plist 中添加一些键来解决它。我遵循的步骤是:

  1. Opened my Project target's info.plistfile

  2. Added a Key called NSAppTransportSecurityas a Dictionary.

  3. Added a Subkey called NSAllowsArbitraryLoadsas Booleanand set its value to YESas like following image.
  1. 打开我的项目目标info.plist文件

  2. 增加了一个名为关键NSAppTransportSecurityDictionary

  3. 添加了一个名为NSAllowsArbitraryLoadsas的子项Boolean并将其值设置YES为如下图所示。

enter image description here

在此处输入图片说明

Clean the Project and Now Everything is Running fine as like before.

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

Ref Link: https://stackoverflow.com/a/32609970

参考链接:https: //stackoverflow.com/a/32609970

EDIT:OR In source code of info.plistfile we can add that:

编辑:或在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>

回答by Arjan

Be aware, using NSAllowsArbitraryLoads = truein the project's info.plistallows all connection to any server to be insecure. If you want to make sure only a specific domainis accessible through an insecure connection, try this:

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

enter image description here

在此处输入图片说明

Or, as source code:

或者,作为源代码:

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

Clean & Build project after editing.

编辑后清理并构建项目。

回答by Teja Kumar Bethina

Transport securityis provided in iOS 9.0 or later, and in OS X v10.11 and later.

iOS 9.0 或更高版本以及 OS X v10.11 和更高版本中提供了传输安全性

So by default only httpscalls only allowed in apps. To turn off App Transport Security add following lines in info.plistfile...

所以默认情况下,只允许在应用程序中使用https调用。要关闭 App Transport Security 在info.plist文件中添加以下行...

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

For more info:
https://developer.apple.com/library/content/documentation/General/Reference/InfoPlistKeyReference/Articles/CocoaKeys.html#//apple_ref/doc/uid/TP40009251-SW33

更多信息:https:
//developer.apple.com/library/content/documentation/General/Reference/InfoPlistKeyReference/Articles/CocoaKeys.html#//apple_ref/doc/uid/TP40009251-SW33

回答by Mr. Bean

For iOS 10.x and Swift 3.x [below versions are also supported] just add the following lines in 'info.plist'

对于 iOS 10.x 和 Swift 3.x [也支持以下版本] 只需在“info.plist”中添加以下几行

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

回答by Enamul Haque

In Swift 4 You can use

在 Swift 4 你可以使用

->Go Info.plist

->去信息.plist

-> Click plus of Information properties list

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

->Add App Transport Security Settingsas dictionary

-> 将应用传输安全设置添加为字典

-> Click Plus icon App Transport Security Settings

-> 单击加号图标应用程序传输安全设置

-> Add Allow Arbitrary Loadsset YES

-> 添加允许任意负载设置YES

Bellow image look like

波纹管图像看起来像

enter image description here

在此处输入图片说明

回答by Avinash651

I have solved as plist file.

我已经解决了 plist 文件。

Add a NSAppTransportSecurity : Dictionary.

添加 NSAppTransportSecurity : 字典。

Add Subkey named " NSAllowsArbitraryLoads " as Boolean : YES

将名为“NSAllowsArbitraryLoads”的子项添加为布尔值:YES

enter image description here

在此处输入图片说明

回答by Keshav Gera

The resource could not be loaded because the App Transport Security policy requires the use of a secure connection working in Swift 4.03.

无法加载资源,因为应用传输安全策略要求使用适用于 Swift 4.03 的安全连接。

Open your pList.info as source code and paste:

打开您的 pList.info 作为源代码并粘贴:

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

回答by Ashok R

From Apple documentation

来自苹果文档

If you're developing a new app, you should use HTTPS exclusively. If you have an existing app, you should use HTTPS as much as you can right now, and create a plan for migrating the rest of your app as soon as possible. In addition, your communication through higher-level APIs needs to be encrypted using TLS version 1.2 with forward secrecy. If you try to make a connection that doesn't follow this requirement, an error is thrown. If your app needs to make a request to an insecure domain, you have to specify this domain in your app's Info.plist file.

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

To Bypass App Transport Security:

绕过应用程序传输安全:

<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>

To allow all insecure domains

允许所有不安全的域

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

Read More: Configuring App Transport Security Exceptions in iOS 9 and OSX 10.11

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

回答by Anit Kumar

If you are using Xcode 8.0 and swift 3.0 or 2.2

如果您使用的是 Xcode 8.0 和 swift 3.0 或 2.2

enter image description here

在此处输入图片说明

回答by A.G

In Xcode 7.1 onwards(swift 2.0)

在 Xcode 7.1 之后(swift 2.0)

enter image description here

在此处输入图片说明