Dus*_*Sun 3 objective-c swift xcode6
以下Objective-C代码的等效Swift代码是什么?
[NSURLRequest setAllowsAnyHTTPSCertificate:YES forHost:[url host]];
Run Code Online (Sandbox Code Playgroud)
解决方案:
将其添加到文件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>
Run Code Online (Sandbox Code Playgroud)
然而,正如解释在这里,这是远远不够的.在您将使用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!))
}
...
Run Code Online (Sandbox Code Playgroud)
}
然后执行以下操作:
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...)
Run Code Online (Sandbox Code Playgroud)
这适合我.请记住,您必须使用Apache 2.4.x,因为它是支持TLS 1.2的唯一版本.希望这会有所帮助.
| 归档时间: |
|
| 查看次数: |
2312 次 |
| 最近记录: |