简体   繁体   English

URLSession委托不适用于swift 4.2

[英]URLSession delegate is not working on swift 4.2

This code is working fine on Swift version 3, I'm not able to make it work on Swift 4 该代码在Swift版本3上运行良好,但我无法在Swift 4上运行

func rest() {
        let path = "https://localhost:8443/someservice"
        let request = NSMutableURLRequest(URL: NSURL(string: path)!)
        let configuration = NSURLSessionConfiguration.defaultSessionConfiguration()
        let session = NSURLSession(configuration: configuration, delegate: self, delegateQueue:NSOperationQueue.mainQueue())
        let task = session.dataTaskWithRequest(request, completionHandler: {data, response, error -> Void in
            let json:JSON = JSON(data: data!)
            if let c = json["content"].string {
                print(c)
            }
        })
        task.resume()
    }
func URLSession(session: NSURLSession, task: NSURLSessionTask, didReceiveChallenge challenge: NSURLAuthenticationChallenge, completionHandler: (NSURLSessionAuthChallengeDisposition, NSURLCredential?) -> Void) {
        completionHandler(NSURLSessionAuthChallengeDisposition.UseCredential, NSURLCredential(forTrust: challenge.protectionSpace.serverTrust!))
    }

You may need latest syntax 您可能需要最新的语法

func urlSession(_ session: URLSession, 
                task: URLSessionTask, 
          didReceive challenge: URLAuthenticationChallenge, 
   completionHandler: @escaping (URLSession.AuthChallengeDisposition, URLCredential?) -> Void)

Your Delegate method is right for below swift 4.0 version but it's wrong for swift 4.0 and higher. 您的Delegate方法适用于swift 4.0以下的版本,但是对于swift 4.0及更高版本是错误的。

Here is working code, You need to use like this. 这是工作代码,您需要像这样使用。

class ViewController: UIViewController,URLSessionDelegate {

    func urlSession(_ session: URLSession, didReceive challenge: URLAuthenticationChallenge, completionHandler: @escaping (URLSession.AuthChallengeDisposition, URLCredential?) -> Void) {
         completionHandler(URLSession.AuthChallengeDisposition.useCredential, URLCredential(trust: challenge.protectionSpace.serverTrust!))
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM