通常,在 iOS 中使用 dataTaskWithRequest 或 sendAsynchronousRequest 执行 GET 或 POST 调用时,我们会使用错误代码来面对与网络相关的错误,例如,
- NSURLErrorNotConnectedToInternet = -1009
- NSURLErrorCannotConnectToHost = -1004
- NSURLErrorTimedOut = -1001
就我而言,我正在断开互联网并执行服务呼叫。因此,预期的错误代码是"NSURLErrorNotConnectedToInternet = -1009"。但是,它会抛出“NSURLErrorCannotConnectToHost = -1004”,如下所示,
Error Domain=NSURLErrorDomain Code=-1004 "Could not connect to the
server." UserInfo=0x1700f0e00 {NSUnderlyingError=0x170255e70 "The
operation couldn’t be completed. (kCFErrorDomainCFNetwork error
-1004.)", NSErrorFailingURLStringKey=https://example.com/reg,
NSErrorFailingURLKey=https://example.com/reg, _kCFStreamErrorDomainKey=1,
_kCFStreamErrorCodeKey=51, NSLocalizedDescription=Could not connect to the server.}
那么,如何在使用 dataTaskWithRequest 或 sendAsynchronousRequest 时获得准确的错误状态。