Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
243 views
in Technique[技术] by (71.8m points)

ios - AFNetworking 2.0 Reachability

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

You're making this more difficult than it needs to be. Try this:

- (void)viewDidLoad {
   [super viewDidLoad];

   [[AFNetworkReachabilityManager sharedManager] startMonitoring];

}

- (BOOL)connected {
    return [AFNetworkReachabilityManager sharedManager].reachable;
}   

If you also want to be notified when the status changes, then implement setReachabilityStatusChangeBlock

Hope this helps!


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...