ios - 如何使用 NSURLSession 快速发送 HTTPS POST 请求

标签 ios swift nsurlsession

我一直在使用 HTTP 进行开发。当使用 HTTP 连接到开发服务器时,下面的代码工作得很好。但是,当我将方案更改为 https 时,它不会向服务器发送成功的 https 帖子。

要从 HTTP POST 切换到 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()
}

最佳答案

您将必须实现 NSURLSessionDelegate 方法之一,以便它接受 SSL 证书。

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)
        }
    }

}

警告:这将盲目地接受您尝试的任何 SSL 证书/连接。这不是一种安全的做法,但它允许您使用 HTTPS 测试您的服务器。

更新:Swift 4+

class YourClass: Superclass, URLSessionDelegate {

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

    func urlSession(_ session: URLSession, didReceiveChallenge challenge: URLAuthenticationChallenge, completionHandler: (URLSession.AuthChallengeDisposition, URLCredential?) -> Void) {
        if challenge.protectionSpace.authenticationMethod == NSURLAuthenticationMethodServerTrust {
            if let trust = challenge.protectionSpace.serverTrust {
                completionHandler(.useCredential, URLCredential(trust: trust))
            }
        }
    }

}

关于ios - 如何使用 NSURLSession 快速发送 HTTPS POST 请求,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30741046/

相关文章:

ios - 如何在iOS中触摸屏时隐藏键盘

ios - 带时间的 NSDate 列,需要仅根据日期取回唯一值

ios - NSURLSessionConfiguration总是返回nil

ios - IOS中的POST方法问题

objective-c - iOS - 如何使用 UISlider 控制 UIBezierPath 绘图?

iphone - UIImage imageNamed : does not find image within blue referenced Xcode-folder

ios - 为什么 `NSObject() == NSObject()` 是假的,而 `ObjectIdentifier(NSObject()) == ObjectIdentifier(NSObject())` 是真的?

swift - 为复杂的tableHeaderView添加Search Bar和Search Display Controller时,UISearchBar获得焦点后消失

ios - UIView阴影渐变

ios - NSURLConnection VS NSURLSession