URLSession делегат не работает на Swift 4.2 - PullRequest
0 голосов
/ 18 января 2019

Этот код отлично работает на 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 ]

0 голосов
/ 18 января 2019

Ваш метод 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!))
    }
}
0 голосов
/ 18 января 2019

Вам может понадобиться последний синтаксис

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