可达性可达和无法到达的块被多次调用?

时间:2015-09-29 02:00:22

标签: ios objective-c reachability

我使用Reachability检查我的应用程序的网络状态,正常工作正常,但在iOS 9.0.1或更高版本中,reachableBlockunreachableBlock被调用两次,这让我遇到了大麻烦

这只发生在iOS 9.0.1和iOS 9.1 Beta中。

这是我的代码示例:

-(void)checkServerConnection{
//This nslog is to check the method is called only once.
    NSLog(@"Check Server Connection");

    Reachability* reach = [Reachability reachabilityWithHostname:@"www.google.com"];
    [reach startNotifier];
    reach.reachableBlock = ^(Reachability*reach)
    {
//This NSLOG is called twice
        NSLog(@"Reachability reachable block");
        dispatch_async(dispatch_get_main_queue(), ^{
//This NSLOG is called twice
            NSLog(@"REACHABLE!");     
        });
    };

    reach.unreachableBlock = ^(Reachability*reach)
    {
//Same story for this one..
        NSLog(@"UNREACHABLE!");
}
}

如果有人解决了这个问题,请告诉我。

1 个答案:

答案 0 :(得分:0)

这就是我的想法,这应该是一个评论,但它太长了。

请让我解释一下代码中发生的事情......
我不太确定这个,但我认为iOS 9.0.1和iOS 9.1保留变量,因为[reach startNotifier]; ..

当您调用方法-(void)checkServerConnection时,您正在创建new Reachability* reach等等。

如果您再次调用该方法,则会创建一个new Reachability* reach并且现有一个...

可能的解决方案是创建一个全局变量(Reachability * reach),每次调用该方法时都会重用该变量。

可能是这样的:

Reachability* reachVar;
// i've changed your variable name hope that's okay, just for example.

-(void)checkServerConnection{

    NSLog(@"Check Server Connection");

    if (reachVar == nil)
    {
        reachVar = [Reachability reachabilityWithHostname:@"www.google.com"];
        [reachVar startNotifier];
    }
    reachVar.reachableBlock = ^(Reachability*reach)
    {
        NSLog(@"Reachability reachable block");
        dispatch_async(dispatch_get_main_queue(), ^{
            NSLog(@"REACHABLE!");     
        });
    };

    reachVar.unreachableBlock = ^(Reachability*reach)
    {
        NSLog(@"UNREACHABLE!");
    }
}