目前我有一个从服务器检索数据的函数。有超时请求五秒钟。我不完全确定超时请求是否正常,因为五秒钟后没有任何反应。当超时请求完成时,我试图让它向用户显示警报视图。这是代码:
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)®ion=US&append_to_response=videos,images,releases")! )
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()
}