Error Domain=NSURLErrorDomain Code=-1004 instead of -1009 in Swift service calls

↘锁芯ラ 提交于 2019-12-23 02:38:12

问题


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.



来源:https://stackoverflow.com/questions/37208917/error-domain-nsurlerrordomain-code-1004-instead-of-1009-in-swift-service-calls

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!