AFNetworking 2.0 Reachability

2019-01-16 07:25发布

I am trying to determine if the user is connected to the internet by using AFNetworking 2.0 and the "AFNetworkReachabilityManager", but it doesen't seem to work. It's always return that there is a valid internet connection, even though the internet is turned off. This is my code:

 -(BOOL)connected {

   __block BOOL reachable;

    [[AFNetworkReachabilityManager sharedManager] setReachabilityStatusChangeBlock:^(AFNetworkReachabilityStatus status) {

        switch (status) {
            case AFNetworkReachabilityStatusNotReachable:
                NSLog(@"No Internet Connection");
                reachable = NO;
                break;
            case AFNetworkReachabilityStatusReachableViaWiFi:
                NSLog(@"WIFI");

                reachable = YES;
                break;
            case AFNetworkReachabilityStatusReachableViaWWAN:
                NSLog(@"3G");
                reachable = YES;
                break;
            default:
                NSLog(@"Unkown network status");
                reachable = NO;
                break;

                [[AFNetworkReachabilityManager sharedManager] startMonitoring];
        }
    }];

    return reachable;

}

This method is called from my viewDidLoad method. Is there something wrong with my code, since it isn't working?

7条回答
孤傲高冷的网名
2楼-- · 2019-01-16 08:05

The other answers are wrong! It's better to use this to check availabilty:

if ([AFNetworkReachabilityManager sharedManager].networkReachabilityStatus == AFNetworkReachabilityStatusNotReachable)

The reason why is because initially networkReachabilityStatus will be set to AFNetworkReachabilityStatusUnknown until the change status block is called and this stops your code from thinking that network is unavailable when it is not.

查看更多
登录 后发表回答