【问题标题】:URLSession delegate is not working on swift 4.2URLSession 委托不适用于 swift 4.2
【发布时间】:2019-01-18 15:16:03
【问题描述】:

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

【问题讨论】:

  • 如果您解释您所看到的问题,您将获得更快、更准确的答案(并且,取决于读者的心血来潮,更少的反对票)。 “不工作”永远不够具体。任何一段代码都可能出错的方式有无数种,在大多数情况下,仅仅阅读它就很难弄清楚(尤其是如果它曾经可以工作的话)。通过在问题中包含编译器错误或运行时错误,您将节省每个人的时间和精力。

标签: ios swift urlsession


【解决方案1】:

你可能需要最新的语法

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

【讨论】:

    【解决方案2】:

    您的 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!))
        }
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-12-04
      • 2014-11-16
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多