当我将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以前的版本,但当我更新到Xcode 7.0,在iOS 9.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.}

我已经尝试了以下问题和答案,但没有得到任何结果,有任何提前的想法,我可以如何删除服务呼叫错误?

无法加载的资源为ios9 应用程序传输安全Xcode 7 beta 6 https://stackoverflow.com/a/32609970


当前回答

我结合了上面提到的许多选项,设法解决了这个问题。我将包括一份清单,上面列出了我必须做的所有事情。

简而言之:

设置NSAllowsArbitraryLoads为真为我的手表扩展(不是我的手表应用程序)。 确保我使用的是https而不是http。


第一步:

首先,最明显的是,我必须在我的手表扩展的信息中添加一个NSAppTransportSecurity密钥作为字典。plist带有一个名为NSAllowsArbitraryLoads的子键作为布尔值设置为true。只在手表扩展中设置这个,而不是手表应用程序的plist。尽管请注意,这允许所有连接,可能是不安全的。

or

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

第二步:

然后我必须确保我试图加载的url是https,而不仅仅是http。对于任何url,仍然是http我使用:

迅速:

let newURLString = oldURLString。stringByReplacingOccurrencesOfString("http", withString: "https")

Obj - c:

ns弦* newurl字符串= [oldurl字符串stringc stringc背弦:@“http”字符串:@“https”;

其他回答

iOS 9.0或更高版本、OS X v10.11及更高版本提供传输安全性。

默认情况下只允许在应用中调用https。要关闭应用程序传输安全,在信息中添加以下行。plist文件…

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

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

注意,在项目的信息中使用nsallowsarbitaryloads = true。Plist允许到任何服务器的所有连接是不安全的。如果你想确保只有一个特定的域可以通过一个不安全的连接访问,试试这个:

或者,作为源代码:

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

编辑后清理并构建项目。

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

在Swift 4中你可以使用

——> Info.plist

->单击信息属性列表中的“+”

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

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

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

下图是这样的

来自苹果文档

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.

绕过应用程序传输安全:

<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中配置应用程序传输安全例外