How to check whether host(server) is available or

2019-05-30 21:20发布

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.

3条回答
Lonely孤独者°
2楼-- · 2019-05-30 21:31

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");
 } 
查看更多
对你真心纯属浪费
3楼-- · 2019-05-30 21:40
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];
查看更多
We Are One
4楼-- · 2019-05-30 21:49

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
}
}];
查看更多
登录 后发表回答