Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/ios/95.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Ios 如何使用NSURLSession在swift中发送HTTPS POST请求_Ios_Swift_Nsurlsession - Fatal编程技术网

Ios 如何使用NSURLSession在swift中发送HTTPS POST请求

Ios 如何使用NSURLSession在swift中发送HTTPS POST请求,ios,swift,nsurlsession,Ios,Swift,Nsurlsession,我一直在使用HTTP进行开发。下面的代码在使用HTTP连接开发服务器时非常有效。但是,当我将方案更改为https时,它不会向服务器发送成功的https帖子 我还需要做什么才能从HTTP POST切换到HTTPS POST class func loginRemote(successHandler:()->(), errorHandler:(String)->()) { let user = User.sharedInstance // this is where

我一直在使用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()
}

您必须实现一个
nsurlsessionelegate
方法,以便它接受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 11和swift 4中做到这一点?为swift 4更新。嗨,它现在在模拟器中工作,但在真实设备上不工作。我正在使用公司vpn。我在设备上遇到此错误:-1003“找不到具有指定主机名的服务器。”