Receiving Error Domain=kCFErrorDomainCFNetwork Code=2 when attempting to read from ReadStream

匿名 (未验证) 提交于 2019-12-03 02:30:02

问题:

I'm attempting to synchronously read from a CFReadStream objected created by CFStreamCreatePairWithSocketToHost. The stream opened fine but when I attempt to invoke CFReadStreamRead on it in a loop, CFReadStreamRead() returns -1 and the resulting error is:

Error Domain=kCFErrorDomainCFNetwork Code=2 "The operation couldn’t be completed. (kCFErrorDomainCFNetwork error 2.)" UserInfo=0x14a920 {kCFGetAddrInfoFailureKey=8}

I'm also receiving this same exact error when using this ReadStream asynchronously- the first callback I receive is this error.

回答1:

The short story: Probably a DNS resolution failure.

The docs say "The streams do not open a connection to the specified host until one of the streams is opened", and for kCFGetAddrInfoFailureKey,

Querying this key returns the last error code returned by getaddrinfo(3) in response to a DNS lookup. To interpret the results, look up the error code in /usr/include/netdb.h.

netdb.h says

#define EAI_NONAME  8  /* hostname nor servname provided, or not known */ 


回答2:

I was able to fix this by putting in Google's DNS servers (8.8.8.8,8.8.4.4) in the wifi connection in the Settings app. The issue was that our devices were on a network that first required you to agree to some terms of service on a proxy login web page, much like hotels and coffee shops do. Safari worked fine after agreeing, but the app didn't, even after agreeing in Safari. Switching to alternate DNS worked (so did putting in the IP address instead of the DNS entry of our server, but I didn't want to hard-code an IP address).



回答3:

I was able to eliminate this error by removing https:// from the host String.

NSStream.getStreamsToHostWithName("https://example.com" ...

You may need to set the appropriate security level:

 inputStream!.setProperty(NSStreamSocketSecurityLevelTLSv1, forKey: NSStreamSocketSecurityLevelKey) outputStream!.setProperty(NSStreamSocketSecurityLevelTLSv1, forKey: NSStreamSocketSecurityLevelKey) 


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