我使用URLSession来"POST“请求,但有时在公路上请求时,我会得到带有不同错误的错误代码,更常见的情况是:”超时“--这是我在控制台”error Domain=NSURLErrorDomain Code=-1009“中看到的错误消息的示例,”因特网连接似乎处于脱机状态“。
但是我不能在代码中捕捉到这个错误,我做错了什么?,我也得到了另一个代码错误,但是它不会改变情况。
错误消息:
2020-11-25 09:52:07.456207+0200 TestApp[40176:2305710] Connection 4: received failure notification
2020-11-25 09:52:07.456344+0200 TestApp[40176:2305710] Connection 4: failed to connect 1:50, reason -1
2020-11-25 09:52:07.456771+0200 TestApp[40176:2305710] Connection 4: encountered error(1:50)
2020-11-25 09:52:07.459696+0200 TestApp[40176:2305710] Task <888AA895-677A-403B-A436-599FF55DB3BB>.<1> HTTP load failed, 0/0 bytes (error code: -1009 [1:50])
2020-11-25 09:52:07.460557+0200 Venom[40176:2305710] Task <888AA895-677A-403B-A436-599FF55DB3BB>.<1> finished with error [-1009]
Error Domain=NSURLErrorDomain Code=-1009 "The Internet connection appears to be offline." UserInfo={_kCFStreamErrorCodeKey=50, NSUnderlyingError=0x600000116880
{Error Domain=kCFErrorDomainCFNetwork Code=-1009 "(null)" UserInfo={_kCFStreamErrorCodeKey=50, _kCFStreamErrorDomainKey=1}}, _NSURLErrorFailingURLSessionTaskErrorKey=LocalDataTask
<888AA895-677A-403B-A436-599FF55DB3BB>.<1>, _NSURLErrorRelatedURLSessionTaskErrorKey=(
"LocalDataTask <888AA895-677A-403B-A436-599FF55DB3BB>.<1>"
), NSLocalizedDescription=The Internet connection appears to be offline.,
NSErrorFailingURLStringKey=https://link_to_my_request, NSErrorFailingURLKey=https://link_to_my_request, _kCFStreamErrorDomainKey=1}
我的代码:
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)
if (err as? URLError)?.code == .timedOut {
// Handle session timeout
// THIS PIACE OF CODE DOES NOT EXECUTED
print("Oops, what is going on")
}
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 {
}
}
发布于 2020-11-27 18:01:37
打印所有可能的rawValue
代码的URLError
:
未知:-1取消:-999 badURL:-1000 timedOut:-1001 unsupportedURL:-1002 cannotFindHost:-1003 cannotConnectToHost:-1004 networkConnectionLost:-1005 dnsLookupFailed:-1006 httpTooManyRedirects:-1007 resourceUnavailable:-1008 notConnectedToInternet:-1009 redirectToNonExistentLocation:-1010 badServerResponse:-1011 userCancelledAuthentication:-1012 userAuthenticationRequired:-1013 zeroByteResource:-1014 cannotDecodeRawData:-1015 userCancelledAuthentication:-1016 userAuthenticationRequired:-1017:-1022:-1100:-1101-1102 dataLengthExceedsMaximum:-1103 secureConnectionFailed:-1200 serverCertificateHasBadDate:-1201 serverCertificateUntrusted:-1202 serverCertificateHasUnknownRoot:-1203 serverCertificateNotYetValid:-1204 clientCertificateRejected:-1205 clientCertificateRequired:-1206 cannotLoadFromNetwork:-2000 cannotCreateFile:-3000 cannotOpenFile:-3001 cannotCloseFile:-3002 cannotWriteToFile:-3003 cannotRemoveFile:-3004 cannotMoveFile:-3005 downloadDecodingFailedMidStream:-3006 downloadDecodingFailedToComplete:-1018 downloadDecodingFailedToComplete:-1019 -1020 -1021:-995:-996:-996 -997
您可以看到您正在寻找notConnectedToInternet
代码。( rawValue -1009)
因此,您的代码可能如下所示:
switch (err as? URLError)?.code {
case .some(.timedOut):
// Handle session timeout
case .some(.notConnectedToInternet):
// Handle not connected to internet
default: break
}
https://stackoverflow.com/questions/65000939
复制相似问题