iOS可达性:主机方法问题
我创建了一种方法来检查主机是否可以访问。我从苹果开发者网站下载了 Reachability 类(.h 和 .m)并导入到我的项目中。我已将 NSString 名称作为 URL(主机名)传递。主机名是 http://www.google.com。但是,无论我传递给此方法的主机名是什么,它总是返回 NO (connectToHost)。代码如下:
- (BOOL) checkHostAvailability:(NSString *)Name{
BOOL connectToHost;
hostReach = [[Reachability reachabilityWithHostName:Name] retain];
[hostReach startNotifier];
NetworkStatus hostStatus = [hostReach currentReachabilityStatus];
NSLog(@"Name: %@", Name);
NSLog(@"hostStatus is %@", hostStatus);
if(hostStatus == NotReachable){
NSLog(@"Here is the checkHostAvailability Method and host NOT reachable");
connectToHost = NO;
}else{
NSLog(@"Here is the checkHostAvailability Method and host is reachable");
connectToHost = YES;
}
return connectToHost;
}
经过几个小时的调查,我发现 NetworkStatus hostStatus 始终等于 null。我认为这就是该方法不起作用的原因。我花了8个小时找出这段代码的问题并搜索了这个网站,但我仍然找不到问题和解决方案。
请帮助并非常感谢。
I have create a method to check if the host is reachable. I had download the Reachability class (both .h & .m) from apple developer websites and import to my project. I have pass the NSString Name as the URL (host Name). The hostName is http://www.google.com. However, no matter what host name I pass to this method and its always return NO (connectToHost). The code as below:
- (BOOL) checkHostAvailability:(NSString *)Name{
BOOL connectToHost;
hostReach = [[Reachability reachabilityWithHostName:Name] retain];
[hostReach startNotifier];
NetworkStatus hostStatus = [hostReach currentReachabilityStatus];
NSLog(@"Name: %@", Name);
NSLog(@"hostStatus is %@", hostStatus);
if(hostStatus == NotReachable){
NSLog(@"Here is the checkHostAvailability Method and host NOT reachable");
connectToHost = NO;
}else{
NSLog(@"Here is the checkHostAvailability Method and host is reachable");
connectToHost = YES;
}
return connectToHost;
}
After a few hours of investigation, I have found out that the NetworkStatus hostStatus always equal to null. I assume this is why this method is not working. And I have spend 8 hours to find out the problem with this code and search out this website, however I still couldn't find the problem and solution.
Please help and much appreciated.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
从主机名中删除“http://”。
Remove the 'http://' from the host name.
如果您想使用
http://www.google.com
作为主机,则可以传递“google.com”作为主机名。请勿包含http://
、结尾斜杠或结尾斜杠后面的任何内容。包含www.
即可。If you wanted to use
http://www.google.com
as your host, you would pass 'google.com' as the hostname. Do not includehttp://
, the ending slash or anything that could follow an ending slash.www.
is fine to include.这是我用于所有连接检查的代码(请参见此处:iOS 开发者库-可达性),它对我来说工作得很好:
This is the code I use for all the connection checks (see here: iOS Developer Library -Reachability) and it is working fine for me :