NSURLRequest setAllowsAnyHTTPSCertificate to Swift

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

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

      

+3


source to share


2 answers


It is impossible within the framework Foundation

. Apple and Apple's private API says your app will be rejected if you use the private API.



-1


source


Decision

Add this to your info.plist file, which will make ATS accept the 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 explains here , this is not enough. In every class where you will use NSURLSession, you must 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 do 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 be using Apache 2.4.x because it is the only version that supports TLS 1.2. Hope this helps.

+5


source







All Articles