Error Domain=NSURLErrorDomain Code=-1004 instead o

2019-06-03 15:45发布

问题:

Generally, while performing GET or POST calls in iOS using dataTaskWithRequest or sendAsynchronousRequest we use to face network related errors with error codes like,

  • NSURLErrorNotConnectedToInternet = -1009
  • NSURLErrorCannotConnectToHost = -1004
  • NSURLErrorTimedOut = -1001

In my case i'm disconnecting the internet and performing service calls. So, the expected error code is "NSURLErrorNotConnectedToInternet = -1009". But, its throwing "NSURLErrorCannotConnectToHost = -1004" like below,

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.}

So, how to get the exact error status while using dataTaskWithRequest or sendAsynchronousRequest.

回答1:

As a rule, IIRC, the OS sends "not connected to Internet" only in two situations:

  • The network is determined to be nonfunctional after:
    • One or more URL requests fail and
    • The OS tries to probe a well-known captive-portal-detection URL and
    • That request also fails
  • No interface has an IP address
    • Including any connected VPNs
    • Excluding loopback interface

Up until the system reaches that state, the failures you see will be "cannot connect to host", because that's all the OS knows for certain.

As a rule, your app should interpret these in the same way — by using reachability to determine when to try again, then trying again when reachability changes.