How to check whether host(server) is available or not in iOS with AFNetworking

南笙酒味 提交于 2019-12-23 03:34:15

问题


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.


回答1:


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");
 } 



回答2:


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



回答3:


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


来源:https://stackoverflow.com/questions/22980222/how-to-check-whether-hostserver-is-available-or-not-in-ios-with-afnetworking

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!