如何检测真实的网络可用性?
当 iPhone 连接到无线路由器且该路由器未连接到互联网时?我需要显示一条错误消息“检查您的互联网连接”我尝试了可达性示例代码。但没有运气, http://developer.apple.com/library/ios /#samplecode/Reachability/Listings/ReadMe_txt.html
当我禁用手机中的 WIFI 时,它工作正常,我尝试了 在 Objective C 中检查互联网连接示例代码“isDataSourceAvailable”即使它不起作用,任何人都可以帮助我解决这个问题,真的很感激。
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
你可以这样做:
这是一个同步请求,因此它会阻塞当前线程。您可以在后台线程中执行整个网络检查,这样阻塞就无关紧要,或者您可以异步发送请求。此外,您可能希望将 HTTP 方法设置为 HEAD,这样您就不会下载整个资源。
You could do something like this:
This is a synchronous request, so that it will block the current thread. You can do the whole network check in a background thread, so that blocking it won’t matter, or you can send the request asynchronously. Also you might want to set the HTTP method to HEAD, so that you won’t download the whole resource.
我建议你像微软那样做,而且真的很邪恶,你甚至可以使用他们的服务器,因为他们可能会确保这些服务器在可预见的未来保持在线。
他们查找主机名,然后访问 Web 服务器上的一个非常小的文件。
请参阅关于serverfault的相同问题(当然是从非编程角度来看) .)
基本上查找主机名的 IP 地址(在该示例中为“dns.msftncsi.com”),然后访问 URL,例如 http://msftncsi.com/ncsi.txt。如果您愿意,这可以通过简单的套接字编程来完成,不需要真正的 HTTP。
在通过查找主机名找到的 IP 上打开端口 80 的套接字。
像这样向套接字发送一个字符串:
然后等待返回。如果有任何返回,即使是一个字节,也意味着您可以访问互联网。
或者至少可以访问该服务器,在本例中是 Microsoft。
I recommend you do the same as Microsoft does, and to be really wicked, you can even use their servers, since they probably will make sure those are on line for the foreseeable future.
They look up a hostname and then access a very small file on a web server.
See the same question on serverfault (from a non programming perspective of course.)
Basically look up the IP address for a hostname (in that example "dns.msftncsi.com"), then access the URL, for example http://msftncsi.com/ncsi.txt. This can be done with simple socket programming if you like, real HTTP not necessary.
Open a socket to port 80, on the IP you found by looking up the hostname.
Send a string to the socket like so:
Then wait for something to return. If anything returns, even a single byte, it means you have Internet access.
Or at least access to this server, which in this example is Microsoft.
https://github.com/adib/asi -http-request/blob/master/External/Reachability/Reachability.h
这是 git 上 ASI HTTPRequest 项目的一部分。它扩展了 Apple 的示例,显然对于商店中的许多应用程序来说已经足够好了(请参阅 ASI 的用户墙:http://allseeing-i.com/ASIHTTPRequest/Who-is-using-it)
任何人,我知道答案已经被接受,但仅供进一步参考。
https://github.com/adib/asi-http-request/blob/master/External/Reachability/Reachability.h
This is a part of the ASI HTTPRequest project on git. It extends Apple's example and apparently is good enough for quite a few apps in the store (see ASI's wall of who's using: http://allseeing-i.com/ASIHTTPRequest/Who-is-using-it)
Anywho, I know an answer was already accepted, but just for further reference.