I'm trying to set up the network session creator to go back to the previous screen if the timeout request runs out. As of now I'm not completely sure where or how to execute it. Here is the code:
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()
}
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()
}
In the View Controller where you call this method I would use it like this.
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)
}