How to send a HTTPS POST request to swift using NSURLSession

I am developing HTTP. The code below works fine when connected to a development server using HTTP. However, when I change the scheme to https, it does not send a successful https post to the server.

What else do I need to do to switch from HTTP POST to HTTPS POST?

class func loginRemote(successHandler:()->(), errorHandler:(String)->()) {

    let user = User.sharedInstance

    // this is where I've been changing the scheme to https
    url = NSURL(String: "http://url.to/login.page") 

    let request = NSMutableURLRequest(URL: url)

    let bodyData = "email=\(user.email)&password=\(user.password)"
    request.HTTPBody = bodyData.dataUsingEncoding(NSUTF8StringEncoding);

    request.HTTPMethod = "POST"

    let session = NSURLSession.sharedSession()

    // posting login request
    let task = session.dataTaskWithRequest(request, completionHandler: {data, response, error -> Void in
        if let httpResponse = response as? NSHTTPURLResponse {
            if httpResponse.statusCode == 200 {
                // email+password were good

                successHandler()                    

            } else {
                // email+password were bad
                errorHandler("Status: \(httpResponse.statusCode) and Response: \(httpResponse)")
            }
        } else {
            NSLog("Unwrapping NSHTTPResponse failed")
        }
    })

    task.resume()
}
+4
source share
1 answer

You will need to implement one of the methods NSURLSessionDelegatein order for it to accept the SSL certificate.

class YourClass: Superclass, NSURLSessionDelegate {

    class func loginRemote(successHandler:()->(), errorHandler:(String)->()) {
        // ...
        let session = NSURLSession(configuration: NSURLSessionConfiguration.defaultSessionConfiguration(), 
                                   delegate: self, 
                                   delegateQueue: nil)
        // ...
    }

    func URLSession(session: NSURLSession, task: NSURLSessionTask, didReceiveChallenge challenge: NSURLAuthenticationChallenge, completionHandler: (NSURLSessionAuthChallengeDisposition, NSURLCredential!) -> Void) {
        if challenge.protectionSpace.authenticationMethod == NSURLAuthenticationMethodServerTrust {
            let credential = NSURLCredential(trust: challenge.protectionSpace.serverTrust)
            completionHandler(NSURLSessionAuthChallengeDisposition.UseCredential, credential)
        }
    }

}

WARNING. This will blindly accept any SSL certificate / connection you are trying to make. This is not a safe practice, but it will allow you to test your server using HTTPS.

+2
source

All Articles