处理 URLSession 超时
Handle URLSession timeout
我使用 URLSession 进行 POST 请求并获取玩家列表,但有时我会收到错误“Error Domain=NSURLErrorDomain Code=-1001”,我该如何处理?
我怎么会在“完成”中出错?
func addPlayer(playerCode: String, completion: @escaping (Error?) -> ()) {
guard let url = URL(string: "\(url)") else { return }
var urlRequest = URLRequest(url: url)
urlRequest.httpMethod = "POST"
let playerCode = [playerCode]
let params = ["players": playerCode]
do {
let data = try JSONSerialization.data(withJSONObject: params, options: .init())
urlRequest.httpBody = data
urlRequest.setValue("application/json", forHTTPHeaderField: "content-type")
let sessionConfig = URLSessionConfiguration.default
sessionConfig.timeoutIntervalForRequest = 5.0
DispatchQueue.global(qos: .background).async {
URLSession(configuration: sessionConfig).dataTask(with: urlRequest) { (data, resp, err) in
guard let data = data else { return }
guard let resp = resp else { return }
print(data)
print(resp)
guard let response = resp as? HTTPURLResponse, (200 ..< 530) ~= response.statusCode else {
print("Error: HTTP request failed")
return
}
if response.statusCode == 200 {
print("Status code is 200")
do {
let json = try JSONDecoder().decode(ListOfPlayers.self, from: data)
// I am do what I am want
} catch let jsonError {
print("Error json serialization \(jsonError)")
}
completion(nil)
} else if response.statusCode == 422 {
print("Status code is 422")
completion(nil)
return
}
}.resume()
}
} catch {
}
}
我也在尝试使用这个代码:
guard let err = err else { return }
if (err._code == -1001) {
print("Oops bad connection")
}
但是这段代码在“超时”期间不执行
您可以将错误转换为 URLError
类型,然后使用 code
属性 安全地检查它是否是会话超时错误:
if (err as? URLError)?.code == .timedOut {
// Handle session timeout
}
我使用 URLSession 进行 POST 请求并获取玩家列表,但有时我会收到错误“Error Domain=NSURLErrorDomain Code=-1001”,我该如何处理?
我怎么会在“完成”中出错?
func addPlayer(playerCode: String, completion: @escaping (Error?) -> ()) {
guard let url = URL(string: "\(url)") else { return }
var urlRequest = URLRequest(url: url)
urlRequest.httpMethod = "POST"
let playerCode = [playerCode]
let params = ["players": playerCode]
do {
let data = try JSONSerialization.data(withJSONObject: params, options: .init())
urlRequest.httpBody = data
urlRequest.setValue("application/json", forHTTPHeaderField: "content-type")
let sessionConfig = URLSessionConfiguration.default
sessionConfig.timeoutIntervalForRequest = 5.0
DispatchQueue.global(qos: .background).async {
URLSession(configuration: sessionConfig).dataTask(with: urlRequest) { (data, resp, err) in
guard let data = data else { return }
guard let resp = resp else { return }
print(data)
print(resp)
guard let response = resp as? HTTPURLResponse, (200 ..< 530) ~= response.statusCode else {
print("Error: HTTP request failed")
return
}
if response.statusCode == 200 {
print("Status code is 200")
do {
let json = try JSONDecoder().decode(ListOfPlayers.self, from: data)
// I am do what I am want
} catch let jsonError {
print("Error json serialization \(jsonError)")
}
completion(nil)
} else if response.statusCode == 422 {
print("Status code is 422")
completion(nil)
return
}
}.resume()
}
} catch {
}
}
我也在尝试使用这个代码:
guard let err = err else { return }
if (err._code == -1001) {
print("Oops bad connection")
}
但是这段代码在“超时”期间不执行
您可以将错误转换为 URLError
类型,然后使用 code
属性 安全地检查它是否是会话超时错误:
if (err as? URLError)?.code == .timedOut {
// Handle session timeout
}