kongkong's Blog

No Silver Bullet --- Computer Language is just a tool.

AFNetworking如何判别网络状态

| Comments

Actually contrary to what A-Live said Reachability IS a part of AFNetworking. It's implemented inAFHTTPClient.h here. You have to have the correct imports in your .pch file as discussed here in order to use it.

To use it you'll probably want to have a subclass of AFHTTPClient so you can usesetReachabilityStatusChangeBlock defined here. Here's a simple example without using a subclass.

AFHTTPClient *client = [AFHTTPClient clientWithBaseURL:[NSURL URLWithString:@"http://google.com"]];
[client setReachabilityStatusChangeBlock:^(AFNetworkReachabilityStatus status) {
    if (status == AFNetworkReachabilityStatusNotReachable) {
        // Not reachable
    } else {
        // Reachable
    }

    if (status == AFNetworkReachabilityStatusReachableViaWiFi) {
        // On wifi
    }
}];

If you don't like how this reachability setup works I would recommand Tony Million's fork of Apple's Reachability. Simple example:

Reachability *reach = [Reachability reachabilityWithHostname:@"google.com"];
if ([reach isReachable]) {
    // Reachable
    if ([reach isReachableViaWiFi]) {
        // On WiFi
    }
} else {
    // Isn't reachable

    [reach setReachableBlock:^(Reachability *reachblock)
    {
        // Now reachable
    }];

    [reach setUnreachableBlock:^(Reachability*reach)
    {
        // Now unreachable
    }];
}

Comments

comments powered by Disqus