如何在swift 2.2中处理timeoutIntervalForResource的超时?

时间:2016-07-01 10:10:47

标签: ios swift uiviewcontroller nsurlsession

在我的应用程序中,我想知道NSURLSession是否已过期,我该怎么办? 我很难处理这种情况。

    import UIKit
    class ViewController: UIViewController {

            override func viewDidLoad() {
                super.viewDidLoad()
                downloadDetails()
            }       

            func downloadDetails() {
                let url = NSURL(string: "http://httpbin.org/get")!
                let config = NSURLSessionConfiguration.defaultSessionConfiguration()
                config.timeoutIntervalForResource = 3
                config.timeoutIntervalForRequest = 3
                let session = NSURLSession(configuration: config)
                let task = session.dataTaskWithURL(url) { (data, response, error) -> Void in
                    do {
                        let dict = try NSJSONSerialization.JSONObjectWithData(data!, options: NSJSONReadingOptions.AllowFragments) as! [String:AnyObject]
                            dispatch_async(dispatch_get_main_queue()) {
                            print(dict)
                        }
                    }
                    catch {
                        print("json error: \(error)")
                    }
                }
                task.resume()
            }

1 个答案:

答案 0 :(得分:3)

let sessionDataTask = session.dataTaskWithRequest(sendLocationRequest) { (data, response, error) in
        if error != nil {//Has error for request
          if error?.code == -1001 {
           //Domain=NSURLErrorDomain Code=-1001 "The request timed out."
          }
        } else {
          if let httpRes = response as? NSHTTPURLResponse {
            //Check code
            if httpRes.statusCode == 200 {
              //OK
            }
            //Other code 404,....
          }
        }
    }