AFNetworking 2.0:isReachable总是返回False

时间:2014-07-04 10:16:15

标签: objective-c ios7 afnetworking-2

我在我的应用程序中使用AFNetworking 2.0进行可达性检查。但是,可达属性始终返回false。请参阅代码

[[AFNetworkReachabilityManager sharedManager] startMonitoring];

 _isInternetReachable = [AFNetworkReachabilityManager sharedManager].reachable ;

 [[AFNetworkReachabilityManager sharedManager] setReachabilityStatusChangeBlock:^(AFNetworkReachabilityStatus status) {
        NSLog(@"Reachability: %@", AFStringFromNetworkReachabilityStatus(status));

        if (status)
            _isInternetReachable = YES;
        else
            _isInternetReachable = NO;

  }];

当我在第二行之后检查_isInternetReachable时,它总是返回false。但是一旦我的应用程序启动,它就进入状态更改块并将_isInternetReachable设置为Yes。 我无法弄清楚这种行为。我在模拟器上测试它。请帮忙。感谢

1 个答案:

答案 0 :(得分:0)

请尝试使用以下代码。

监控代码

self.manager = [[AFHTTPRequestOperationManager alloc] initWithBaseURL:[NSURL URLWithString:@"http://www.google.com"]];

self.manager.responseSerializer = [AFJSONResponseSerializer serializer];

__block ViewController *blocksafeSelf = self;

    NSOperationQueue *operationQueue = self.manager.operationQueue;

    [self.manager.reachabilityManager setReachabilityStatusChangeBlock:^(AFNetworkReachabilityStatus status) {

//        NSLog(@"stats: %d", self.manager.reachabilityManager.isReachable);
        [blocksafeSelf finish];

        switch (status) {
            case AFNetworkReachabilityStatusNotReachable:
                // we need to notify a delegete when internet conexion is lost.
                // [delegate internetConexionLost];
                NSLog(@"No Internet Conexion");
                break;
            case AFNetworkReachabilityStatusReachableViaWiFi:
                NSLog(@"WIFI");
                break;
            case AFNetworkReachabilityStatusReachableViaWWAN:
                NSLog(@"3G");
                break;
            default:
                NSLog(@"Unkown network status");
                [operationQueue setSuspended:YES];
                break;
        }
    }];// Do any additional setup after loading the view, typically from a nib.
    [self.manager.reachabilityManager startMonitoring];

回调方法:

-(void)finish

{

NSLog(@"---:%d", self.manager.reachabilityManager.isReachable);

}