Vergil Vergil - 4 months ago 16
iOS Question

AFNetworking checking the network available

i'm using the AFN to check the network.

__block BOOL connect;

AFNetworkReachabilityManager*manager = [AFNetworkReachabilityManager sharedManager];
[manager setReachabilityStatusChangeBlock:^(AFNetworkReachabilityStatus status) {
switch (status) {
case -1:
connect=YES;
break;
case 0:
connect=NO;
break;
case 1:
connect=YES;
break;
case 2:
connect=YES;
break;
default:
break;
}
}];


[manager startMonitoring];


and i want to get the Bool connect at another file

if (![ValueUtils isConnectNet])


but it didn't get the bool immediately how can i get the bool first and then do the “if else” thing?




now i use Reachability ,if u use AFN's isReachable right after startMonitoring,it can't get the current network status immediately.

Answer

You can check the reachability by this:

AFNetworkReachabilityManager *reachability = [AFNetworkReachabilityManager sharedManager];
    [reachability setReachabilityStatusChangeBlock:^(AFNetworkReachabilityStatus status) {
        switch (status) {
            case AFNetworkReachabilityStatusReachableViaWWAN:
                NSLog(@"WWN");
                break;
             case AFNetworkReachabilityStatusReachableViaWiFi:
                NSLog(@"WiFi");
                break;
             case AFNetworkReachabilityStatusUnknown:
                NSLog(@"Unknown");
                break;
                case AFNetworkReachabilityStatusNotReachable:
                NSLog(@"Not Reachable");
                break;
            default:
                break;
        }
    }];

or you can use:

+(BOOL)IsInternet
{
    Reachability *networkReachability = [Reachability reachabilityForInternetConnection];
    NetworkStatus networkStatus = [networkReachability currentReachabilityStatus];
    if (networkStatus == NotReachable)
    {
        return NO;
    }
    else
    {
        return YES;
    }
}