可达性iOS并不能正常工作

时间:2015-03-17 11:40:52

标签: ios reachability

我们正在开发一个模块,用于检查Internet连接是处于活动状态还是未处于活动状态或已禁用。之前的方案运行良好,除非存在WI-FI连接但互联网未激活的情况除外。我们已确保未启用数据移动连接(3G,4G)。

我们已经看到每个人都建议使用Tony Million的Reachability类,它取代了Apple的类。

下面是我们正在使用的代码:

-(BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
Reachability *reachability = [Reachability reachabilityWithHostname:@"www.google.com"]; //Cambiar por el servidor

    reachability.reachableBlock = ^(Reachability *reachability) {
        NSLog(@"Network is reachable.");

    };

    reachability.unreachableBlock = ^(Reachability *reachability) {
       NSLog(@"Network is unreachable.");

    };

    // Start Monitoring
    [reachability startNotifier];

    return YES;
}

是否存在WI-FI连接,但互联网未激活,因此无法正常运行:

reachability.reachableBlock = ^(Reachability *reachability) {
    NSLog(@"Network is reachable.");
}

而不是

reachability.unreachableBlock = ^(Reachability *reachability) {
   NSLog(@"Network is unreachable.");

}

我们缺少什么?

提前谢谢你,

此致

2 个答案:

答案 0 :(得分:0)

试试这个,

- (BOOL)isNetAvailable
{
    BOOL isNetAvailable = NO;

    Reachability *reach = [Reachability reachabilityWithHostName:@"www.google.com"];
    NetworkStatus netStatus = [reach currentReachabilityStatus];
    if (netStatus != NotReachable)
    {
        isNetAvailable = YES;
    }
    else
    {
        isNetAvailable = NO;
    }
    return  isNetAvailable;
}

答案 1 :(得分:0)

您可以使用:

NSURLRequest *nsrequest = [NSURLRequest requestWithURL:[NSURL URLWithString: @"http://www.google.com"]];
NSHTTPURLResponse *response = nil;
NSError *error;
NSData *data = [NSURLConnection sendSynchronousRequest:nsrequest returningResponse:&response error:&error];

if(response.statusCode==0){
    NSLog(@"Network is unreachable.");
}
else{
    NSLog(@"Network is reachable.");
}