Question

I am using AFNetworking in my App for communicating with server. How can i check whether my host(server) is available or not, i should check this before i am sending a request to server.

Was it helpful?

Solution

Using AFNetworking 2.0 that provide method like below you can check instead of using Reachability class.

- (void)viewDidLoad {
   [super viewDidLoad];

    [[AFNetworkReachabilityManager sharedManager] startMonitoring];

}

After set start-monitoring in to viewDidLoad you can check any where in to class using Bellow Method.

 if ([[AFNetworkReachabilityManager sharedManager] isReachable]) 
 {
   NSLog(@"IS REACHABILE");
 } 
 else 
 {
   NSLog(@"NOT REACHABLE");
 } 

OTHER TIPS

You can try the following code:

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
}];
}

OR You can do like this:

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
}
}];
NSOperationQueue *operationQueue = self.operationQueue;

// This block is automatically invoked every time the network status changes 
[self.reachabilityManager setReachabilityStatusChangeBlock:^(AFNetworkReachabilityStatus status) {
    switch (status) {
            case AFNetworkReachabilityStatusNotReachable:
            // we need to notify a delegete when internet connection is lost.
            // use this delegate to notify the user. 
            //[delegate internetConnectionLost];
            NSLog(@"No Internet Connection");
            break;
            case AFNetworkReachabilityStatusReachableViaWiFi:
            NSLog(@"Host available through WIFI");
            break;
            case AFNetworkReachabilityStatusReachableViaWWAN:
            NSLog(@"Host available through 3G");
            break;
        default:
            NSLog(@"Unkown network status");
            [operationQueue setSuspended:YES];
            break;
    }
}];
[self.reachabilityManager startMonitoring];
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top