gpt4 book ai didi

swift - 尝试访问 Alamofire 中的错误代码

转载 作者:可可西里 更新时间:2023-11-01 01:23:12 28 4
gpt4 key购买 nike

我正在使用 Alamofire 4。当我使用时

print(response.debugDescription)

我在控制台中有这样的东西:

[Request]: https://api2.website.com
[Response]: nil
[Data]: 0 bytes
[Result]: FAILURE: Error Domain=NSURLErrorDomain Code=-1009 "The Internet connection appears to be offline." UserInfo={NSUnderlyingError=0x17444ace0 {Error Domain=kCFErrorDomainCFNetwork Code=-1009 "(null)" UserInfo={NSErrorPeerAddressKey=<CFData 0x170490e50 [0x1ab165bb8]>{length = 16, capacity = 16, bytes = 0x100201bb341d1f890000000000000000}, _kCFStreamErrorCodeKey=57, _kCFStreamErrorDomainKey=1}}, NSErrorFailingURLStringKey=https://api2.flowwow.com/api2/client/info/?auth_token=da88d8aa49ff6f8bb4e1&hash=7f38be3f68db39a6d88687505fdb9ba5&partner_id=1004, NSErrorFailingURLKey=https://api2.website.com, _kCFStreamErrorDomainKey=1, _kCFStreamErrorCodeKey=57, NSLocalizedDescription=The Internet connection appears to be offline.}
[Timeline]: Timeline: { "Request Start Time": 510763454.078, "Initial Response Time": 510763455.293, "Request Completed Time": 510763455.293, "Serialization Completed Time": 510763455.297, "Latency": 1.215 secs, "Request Duration": 1.215 secs, "Serialization Duration": 0.005 secs, "Total Duration": 1.220 secs }

有一行特别让我感兴趣:

Error Domain=NSURLErrorDomain Code=-1009

如何获得此代码,以便正确处理错误。我尝试了所有可以组成的组合,但在任何地方都找不到此代码的踪迹。

最佳答案

当您使用 Alamofire 进行调用时,它会返回一个响应,您可以在其中检查是否有任何错误。这是使用 Alamofire 调用错误处理的简单示例。

Alamofire.request("https://your.url.com").responseJSON { response in
if (response.result.isSuccess){
//do your json stuff
} else if (response.result.isFailure) {
//Manager your error
switch (response.error!._code){
case NSURLErrorTimedOut:
//Manager your time out error
break
case NSURLErrorNotConnectedToInternet:
//Manager your not connected to internet error
break
default:
//manager your default case
}
}
}

享受 :)

2020 年 4 月 1 日更新

这段代码应该适用于 Alamofire 5 版本。我还没有检查,让我知道这是否有效

AF.request(route).responseJSON { (response) in
let result = response.result
switch result {
case .success(let value):
print("Success")
// Do something with value
case .failure(let error):

if let underlyingError = error.underlyingError {
if let urlError = underlyingError as? URLError {
switch urlError.code {
case .timedOut:
print("Timed out error")
case .notConnectedToInternet:
print("Not connected")
default:
//Do something
print("Unmanaged error")
}
}
}
}
}

我希望这有效:)

关于swift - 尝试访问 Alamofire 中的错误代码,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42698516/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com