iOS可访问性:主机方法问题

时间:2011-09-21 14:35:29

标签: ios host reachability

我创建了一种检查主机是否可访问的方法。我从Apple开发者网站下载了Reachability类(.h和.m)并导入到我的项目中。我已将NSString名称作为URL(主机名)传递。 hostName是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个小时来查找此代码的问题并搜索出这个网站,但是我仍然找不到问题和解决方案。

请帮忙,非常感谢。

3 个答案:

答案 0 :(得分:1)

从主机名中删除“http://”。

答案 1 :(得分:1)

如果您想使用http://www.google.com作为主持人,则可以将“google.com”作为主机名。不要包含http://,结尾斜杠或任何可能跟随结束斜杠的东西。可以包括www.

[Reachability reachabilityWithHostName:@"google.com"];

答案 2 :(得分:0)

这是我用于所有连接检查的代码(请参阅此处:iOS Developer Library -Reachability),它对我来说很好用:

-(BOOL) hasConnection{

//check network status _ iphone settings
Reachability *internetReachability = [Reachability reachabilityForInternetConnection];
[internetReachability startNotifier];


NetworkStatus status=[internetReachability currentReachabilityStatus];
if (status == NotReachable) {
    NSLog(@"No internet");
    //[internetReachability stopNotifier];
    return NO;
}else {
    NSLog(@"Internet is ON");
   // [internetReachability stopNotifier];

    //check internet connection _reachable path

    Reachability *hostReachable=[Reachability   reachabilityWithHostName:@"www.apple.com"];
    BOOL connectionRequired =[hostReachable connectionRequired];
    NSLog(@"%hhd",connectionRequired);

    [hostReachable startNotifier];

    Reachability *wifiReachability=[Reachability reachabilityForLocalWiFi];
    [wifiReachability startNotifier];

    NetworkStatus hostStatus=[hostReachable currentReachabilityStatus];
    if(hostStatus == NotReachable){
        NSLog(@"No internet connection");
        [hostReachable stopNotifier];
        return NO;
    }else{
        NSLog(@"Connection is ok");
        [hostReachable stopNotifier];
        return YES;
    }
}
}