【发布时间】:2015-06-01 02:38:44
【问题描述】:
下面的 Objective-C 代码的等效 Swift 代码是什么?
[NSURLRequest setAllowsAnyHTTPSCertificate:YES forHost:[url host]];
【问题讨论】:
-
你找到 Swift 代码了吗?我真的需要这个来测试......
标签: objective-c swift xcode6
下面的 Objective-C 代码的等效 Swift 代码是什么?
[NSURLRequest setAllowsAnyHTTPSCertificate:YES forHost:[url host]];
【问题讨论】:
标签: objective-c swift xcode6
解决方案:
将此添加到文件 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 的版本。 希望这会有所帮助。
【讨论】:
这在 Foundation 框架上不可用。它来自 Apple 私有 API,Apple 表示如果您使用私有 API,您的应用程序将被拒绝。
【讨论】: