繁体   English   中英

URLSession委托不适用于swift 4.2

[英]URLSession delegate is not working on swift 4.2

该代码在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!))
    }

您可能需要最新的语法

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

您的Delegate方法适用于swift 4.0以下的版本,但是对于swift 4.0及更高版本是错误的。

这是工作代码,您需要像这样使用。

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