代码之家  ›  专栏  ›  技术社区  ›  serginhofogo

URLSession委托未使用swift 4.2

  •  0
  • serginhofogo  · 技术社区  · 6 年前

    这个代码在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!))
        }
    
    2 回复  |  直到 6 年前
        1
  •  1
  •   Shehata Gamal    6 年前

    您可能需要最新的语法

    func urlSession(_ session: URLSession, 
                    task: URLSessionTask, 
              didReceive challenge: URLAuthenticationChallenge, 
       completionHandler: @escaping (URLSession.AuthChallengeDisposition, URLCredential?) -> Void)
    
        2
  •  0
  •   Nikunj Kumbhani    6 年前

    您的委托方法适用于低于swift 4.0版本,但对于swift4.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!))
        }
    }