如果超时请求用完,我正在尝试设置网络会话创建器以返回上一屏幕。截至目前,我还不完全确定在何处或如何执行它。这是代码:
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()
}
答案 0 :(得分: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()
}
在您调用此方法的View Controller中,我会像这样使用它。
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)
}
答案 1 :(得分:0)
你可以试试这个。这对我有用
_ = self.navigationController?.popViewController(animated: true)
这将从UIViewController
堆栈中弹出最顶层UINavigationController
,因此您的上一个屏幕将会显示。
答案 2 :(得分:0)
如果您使用show segue访问当前的VC,则可以使用:
_ = self.navigationController?.popViewController(animated: true)
如果你使用了模态segue,你会使用:
_ = self.navigationController?.dismiss(animated: true)