当任务因超时而失败时如何显示消息

时间:2019-05-27 18:34:14

标签: swift

对于此示例,我需要一种干净的方法来在由于超时而导致任务结束时打印(“ ERROR”)。

func getUserDataService() -> Bool{
    var getDataStatus = false

    //Create the url with NSURL
    let url = URL(string: "http://someurl")! //change the url

    //Create the session object
    let session = URLSession.shared

    //Now create the URLRequest object using the url object
    var request = URLRequest(url: url)
    request.httpMethod = "GET"
    request.timeoutInterval = 15

    //create dataTask using the session object to send data to the server
    let task = session.dataTask(with: request as URLRequest, completionHandler: { data, response, error in

        guard error == nil else {
            return
        }

        guard let data = data else {
            return
        }

        do {
            //create json object from data
            if let json = try JSONSerialization.jsonObject(with: data, options: .mutableContainers) as? [String: Any] {


                if let httpResponse = response as? HTTPURLResponse {
                    if httpResponse.statusCode == 200 {

                        getDataStatus = true

                    } else {

                    }
                }
            }
        } catch let error {
            print(error)
        }
    })
    task.resume()
    return getDataStatus
}

失败时会显示以下内容,但我不确定该在哪里控制。

  

2019-05-27 13:53:58.501322-0400 AppName [60195:841789]任务。<3>已完成,错误-代码:-1001
  2019-05-27 13:53:58.505525-0400 AppName [60195:842001]任务。<3> HTTP加载失败(错误代码:-999 [1:89])< / p>

1 个答案:

答案 0 :(得分:0)

请阅读文档URL Loading System Error Codes。超时错误为-1001NSURLErrorTimedOut

该错误在数据任务的完成处理程序中返回。处理吧!

let task = session.dataTask(with: request as URLRequest, completionHandler: { data, response, error in
    if let nserror = error as NSError?,
      nserror.code == NSURLErrorTimedOut {
      // do something
      return
    }

除了不能从该方法返回Bool值之外,还必须添加完成处理程序

func getUserDataService(completion: @escaping (Bool) -> Void) {

...

然后致电

completion(true)

并删除

return getDataStatus