Swift 3 URL会话 - 针对URL添加时间

时间:2016-08-20 18:01:22

标签: swift nsurlconnection nsurlsession swift3

以下代码工作正常,但如果数据连接太慢,我需要添加超时。

  func preload(){

        let url = URL(string: "https://example.com/loadteams.php")
        let data = try? Data(contentsOf: url!)

        if data == nil{
                 showAlert()

            }else{
        values = try! JSONSerialization.jsonObject(with: data!, options: JSONSerialization.ReadingOptions.mutableContainers) as! [[String : AnyObject]]

        }

       }

我认为我需要将URLSession带入此中,但我不知道该如何操作,我知道它应该是有用的。

 let urlconfig = URLSessionConfiguration.default
        urlconfig.timeoutIntervalForRequest = 5
        urlconfig.timeoutIntervalForResource = 5
        self.session = URLSession(configuration: urlconfig, delegate: self.delegates, delegateQueue: nil)  

这有错误没有代表

1 个答案:

答案 0 :(得分:3)

您可以致电dataTask(with:)

let session: URLSession = {
    let configuration = URLSessionConfiguration.default
    configuration.timeoutIntervalForRequest = 5
    configuration.timeoutIntervalForResource = 5
    return URLSession(configuration: configuration, delegate: nil, delegateQueue: nil)
}()

func preload(completionHandler: @escaping ([[String: AnyObject]]?) -> Void) {
    let url = URL(string: "https://example.com/loadteams.php")!

    let task = session.dataTask(with: url) { data, response, error in
        if let data = data, let json = try? JSONSerialization.jsonObject(with: data, options: []), let array = json as? [[String: AnyObject]] {
            DispatchQueue.main.async {
                completionHandler(array)
            }
        } else {
            DispatchQueue.main.async {
                completionHandler(nil)
            }
        }
    }
    task.resume()
}

但是,您可能已经注意到,与您的演绎不同,这是异步的。所以你可能应该使用一个完成处理程序模式,所以你知道它什么时候完成。所以,我亲自从来电者那里进行UI更新,例如:

preload() { values in
    guard let values = values else {
        self.showAlert()
        return
    }

    self.values = values
    // trigger whatever UI update you want here
}