超时请求后如何返回上一个屏幕?
Posted
技术标签:
【中文标题】超时请求后如何返回上一个屏幕?【英文标题】:How to go back to previous screen after a timeout request? 【发布时间】:2017-03-14 13:58:43 【问题描述】:我正在尝试将网络会话创建者设置为在超时请求用完时返回上一个屏幕。截至目前,我不完全确定在哪里或如何执行它。代码如下:
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()
【问题讨论】:
你在使用 UINavigationController 吗? 我正在使用 UINavigationController 【参考方案1】: 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)
【讨论】:
这个请求是在单例中发出的,但是被视图控制器访问 我编辑了我的答案,我添加了 2 个闭包:一个如果请求成功,另一个如果它失败。根据情况,您可以同时管理它们。【参考方案2】:你可以试试这个。这对我有用
_ = self.navigationController?.popViewController(animated: true)
这将从UINavigationController
堆栈中弹出最顶部的UIViewController
,因此您之前的屏幕将可见。
【讨论】:
【参考方案3】:如果您使用 show segue 来访问您当前的 VC,您可以使用:
_ = self.navigationController?.popViewController(animated: true)
如果你使用模态转场,你会使用:
_ = self.navigationController?.dismiss(animated: true)
【讨论】:
以上是关于超时请求后如何返回上一个屏幕?的主要内容,如果未能解决你的问题,请参考以下文章