【问题标题】:NSURLRequest setAllowsAnyHTTPSCertificate to SwiftNSURLRequest setAllowsAnyHTTPSCertificate 到 Swift
【发布时间】:2015-06-01 02:38:44
【问题描述】:

下面的 Objective-C 代码的等效 Swift 代码是什么?

[NSURLRequest setAllowsAnyHTTPSCertificate:YES forHost:[url host]];

【问题讨论】:

  • 你找到 Swift 代码了吗?我真的需要这个来测试......

标签: objective-c swift xcode6


【解决方案1】:

解决方案

将此添加到文件 info.plist 中,这将强制 ATS 接受自签名证书:

<key>NSAppTransportSecurity</key>
<dict>
    <key>NSExceptionDomains</key>
    <dict>
        <key>localhost</key>
        <dict>
            <!--Include to allow subdomains-->
            <key>NSIncludesSubdomains</key>
            <true/>
            <!--Include to allow HTTP requests-->
            <key>NSExceptionAllowsInsecureHTTPLoads</key>
            <true/>
            <!--
            <key>NSExceptionMinimumTLSVersion</key>
            <string>TLSv1.1</string>
            <key>NSExceptionRequiresForwardSecrecy</key>
            <false/> -->
        </dict>
    </dict>
</dict>

但是,正如 here 解释的那样,这还不够。在您将使用 NSURLSession 的每个类中,您必须声明以下委托:

class LoginService: NSObject, NSURLSessionDelegate {

func URLSession(session: NSURLSession,
    task: NSURLSessionTask,
    didReceiveChallenge challenge: NSURLAuthenticationChallenge,
    completionHandler: (NSURLSessionAuthChallengeDisposition, NSURLCredential?)
    -> Void) {

    completionHandler(NSURLSessionAuthChallengeDisposition.UseCredential, NSURLCredential(forTrust: challenge.protectionSpace.serverTrust!))
}

...

}

然后执行如下操作:

let configuration = NSURLSessionConfiguration.defaultSessionConfiguration()

    let urlRequest: NSURLRequest = NSURLRequest(URL: requestURL)

    let session = NSURLSession(configuration: configuration, delegate: self, delegateQueue:NSOperationQueue.mainQueue())

    /*
    dataTaskWithRequest: creates an HTTP request for the specified URL request object, and calls a handler upon completion.
    */
    let task = session.dataTaskWithRequest(urlRequest...)

这对我有用。请记住,您必须使用 Apache 2.4.x,因为它是唯一支持 TLS 1.2 的版本。 希望这会有所帮助。

【讨论】:

  • 这是迄今为止对 StackOverflow 最好、最完整的描述。当然,您需要了解风险,等等。但是,如果您只是需要尝试一些东西,那就完美了!感谢关于风险:developer.apple.com/library/ios/documentation/General/Reference/…
  • 你很友善,谢谢。我知道风险,但我工作的公司不想拥有一个带 ssl 证书的服务器,因为他们说这太贵了,对吗?
  • 安全性总是会在 CPU 能力方面产生一些开销。我发现了这个不错的网站:istlsfastyet.com我想知道该公司是否有任何其他可能的优化。
  • 嗯,当他们说成本太高时,他们的意思是购买或租用带有 ssl 证书的服务器非常昂贵......
  • 要检查目标服务器的 TLS 参数,请在终端中执行此操作:“openssl s_client -connect :”并最后检查“SSL-Session:...”字段的答案。
【解决方案2】:

这在 Foundation 框架上不可用。它来自 Apple 私有 API,Apple 表示如果您使用私有 API,您的应用程序将被拒绝。

【讨论】:

  • 虽然是真的,但这无关紧要,因为最初的问题可能与本地主机上的测试环境等有关
猜你喜欢
  • 2015-08-31
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-12-11
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多