Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

NSURLRequest setAllowsAnyHTTPSCertificate to Swift

What is the equivalent Swift code of the Objective-C code below?

[NSURLRequest setAllowsAnyHTTPSCertificate:YES forHost:[url host]];
like image 452
Dustin Sun Avatar asked Aug 09 '26 15:08

Dustin Sun


1 Answers

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.

like image 88
SagittariusA Avatar answered Aug 12 '26 03:08

SagittariusA



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!