Internet Connection称为两次Time

时间:2015-11-06 04:32:15

标签: ios objective-c reachability

我想在互联网处于活动状态时调用方法。但我的方法是调用,但它执行两次。我无法理解这是怎么回事。请帮忙。这是我的代码。

Reachability * reachability;
     [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(handleNetworkChanged:) name:kReachabilityChangedNotification object:nil];
        - (void)applicationDidBecomeActive:(UIApplication *)application {
            // Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.

            [self handleNetworkChanged:nil];
        }

        - (BOOL)handleNetworkChanged:(NSNotification *) notice
        {
            reachability = [Reachability reachabilityForInternetConnection];
            [reachability startNotifier];
            NetworkStatus remoteHostStatus = [reachability currentReachabilityStatus];
            if(remoteHostStatus == NotReachable) {
                self.internetConnection = FALSE;

                  [[NSNotificationCenter defaultCenter] postNotificationName:@"NetworkGone" object:nil];
                //NSLog(@"Internet is not Connected");
            } else {
                self.internetConnection = TRUE;

                 [[NSNotificationCenter defaultCenter] postNotificationName:@"NetworkCome" object:nil];
                //NSLog(@"Internet is Connected");
            }
            return  self.internetConnection;
        }

1 个答案:

答案 0 :(得分:-2)

从applicationDidBecomeActive中删除[self handleNetworkChanged:nil]。

[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(handleNetworkChanged:) name:kReachabilityChangedNotification object:nil];

- (void)applicationDidBecomeActive:(UIApplication *)application {

    }

- (BOOL)handleNetworkChanged:(NSNotification *) notice
{
    reachability = [Reachability reachabilityForInternetConnection];
    [reachability startNotifier];
    NetworkStatus remoteHostStatus = [reachability currentReachabilityStatus];
    if(remoteHostStatus == NotReachable) {
        self.internetConnection = FALSE;

          [[NSNotificationCenter defaultCenter] postNotificationName:@"NetworkGone" object:nil];
        //NSLog(@"Internet is not Connected");
    } else {
        self.internetConnection = TRUE;

         [[NSNotificationCenter defaultCenter] postNotificationName:@"NetworkCome" object:nil];
        //NSLog(@"Internet is Connected");
    }
    return  self.internetConnection;
}