What is the equivalent Swift code of the Objective-C code below?
[NSURLRequest setAllowsAnyHTTPSCertificate:YES forHost:[url host]];
What is the equivalent Swift code of the Objective-C code below?
[NSURLRequest setAllowsAnyHTTPSCertificate:YES forHost:[url host]];
SOLUTION:
Add this to file info.plist which will force ATS to accept self signed certificate:
<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>
However, as explain here this is not enough. In each class where you will use NSURLSession you have to declare the following delegate:
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!))
}
...
}
And then perform something like the following:
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...)
This works for me. Remember that you must use Apache 2.4.x because it's the only version supporting TLS 1.2. Hope this will help.
This is not available on the Foundation
framework. It's from Apple private API and Apple says that your application will get rejected if you use private API.