0

如果超时请求用完,我正在尝试设置网络会话创建者返回上一个屏幕。截至目前,我不完全确定在哪里或如何执行它。这是代码:

  lazy var configuration: URLSessionConfiguration = URLSessionConfiguration.default

  lazy var session: URLSession = URLSession(configuration: self.configuration)

 typealias JSONData = ((Data) -> Void)

  func getJSONData(type: String, urlExtension: String, completion: @escaping JSONData) {

    configuration.timeoutIntervalForRequest = 5
    configuration.timeoutIntervalForResource = 5

    let request = URLRequest(url: URL(string:"\(baseURL)\(type)/\(urlExtension)?api_key=\(apiKey)")! )

    let dataTask = session.dataTask(with: request, completionHandler: { (data, response, error) in

      if error == nil {
        if let httpResponse = response as? HTTPURLResponse {
          switch (httpResponse.statusCode) {
          case 200:
            if let data = data {
              completion(data)
            }
          default:
            print(httpResponse.statusCode)
          }
        }
      } else {
        print("Error: \(error?.localizedDescription)")
      }
    })
    dataTask.resume()
  }
4

3 回答 3

0
 lazy var configuration: URLSessionConfiguration = URLSessionConfiguration.default

  lazy var session: URLSession = URLSession(configuration: self.configuration)

 typealias JSONData = ((Data) -> Void)

  func getJSONData(type: String, urlExtension: String, onSucceed : @escaping JSONData ,  onFailure: @escaping (_ error:NSError)-> Void ) {

    configuration.timeoutIntervalForRequest = 5
    configuration.timeoutIntervalForResource = 5

    let request = URLRequest(url: URL(string:"\(baseURL)\(type)/\(urlExtension)?api_key=\(apiKey)")! )

    let dataTask = session.dataTask(with: request, completionHandler: { (data, response, error) in

      if error == nil {
        if let httpResponse = response as? HTTPURLResponse {
          switch (httpResponse.statusCode) {
          case 200:
            if let data = data {
              onSucceed(data)
            }
          default:
            print(httpResponse.statusCode)
          }
        }
      } else {
        onFailure(error! as NSError)
      }
    })
    dataTask.resume()
  }

在您调用此方法的视图控制器中,我会像这样使用它。

NetworkManager.getJSONData(type: "", urlExtension: "",onSucceed {
   //doSmth
}, on Failure{(error) in 
   //show Error
// if it is pushed
    _ = self.navigationController?.popViewController(animated: true) 

// or if its presented 
// self.navigationController?.dismiss(animated: true, completion: nil)

}
于 2017-03-14T14:06:46.410 回答
0

你可以试试这个。这对我有用

_ = self.navigationController?.popViewController(animated: true)

UIViewController这将从堆栈中弹出最顶部UINavigationController,因此您之前的屏幕将可见。

于 2017-03-14T14:06:50.787 回答
0

如果您使用 show segue 来访问您当前的 VC,您可以使用:

_ = self.navigationController?.popViewController(animated: true)

如果您使用模态segue,您将使用:

_ = self.navigationController?.dismiss(animated: true)
于 2017-03-14T14:07:57.957 回答