如何通过AFNetworking在iOS中检查主机(服务器)是否可用

我在我的应用程序中使用AFNetworking与服务器通信。 我如何检查我的主机(服务器)是否可用,我应该检查之前,我发送请求到服务器。

使用提供如下方法的AFNetworking 2.0,您可以检查而不是使用Reachability类。

- (void)viewDidLoad { [super viewDidLoad]; [[AFNetworkReachabilityManager sharedManager] startMonitoring]; } 

设置开始监视到viewDidLoad您可以使用Bellow方法检查任何地方上课。

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

你可以尝试下面的代码:

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

或者你可以这样做:

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