Comment vérifier si l'hôte (server) est disponible ou non dans iOS avec AFNetworking

J'utilise AFNetworking dans mon App pour communiquer avec le server. Comment puis-je vérifier si mon hôte (server) est disponible ou non, je devrais vérifier cela avant d'envoyer une requête au server.

En utilisant AFNetworking 2.0 qui fournit une méthode comme ci-dessous, vous pouvez vérifier au lieu d'utiliser la class Reachability.

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

Après avoir défini start-monitoring dans viewDidLoad vous pouvez cocher n'importe où dans class en utilisant Bellow Method.

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

Vous pouvez essayer le code suivant:

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

OU Vous pouvez faire comme ceci:

 AFHTTPClient *client = [AFHTTPClient clientWithBaseURL:[NSURL URLWithSsortingng:@"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];