2012-07-01 32 views
16

descargados de accesibilidad de Apple, el uso de este método para comprobar si hay una conexión activa:de accesibilidad no funciona como se esperaba

-(BOOL)isReachable{ 

    Reachability *r = [Reachability reachabilityWithHostName:@"http://www.google.com"]; 

    if(NotReachable == [r currentReachabilityStatus]) { 
     NSLog(@"Not Reachable"); 
     return NO; 
    } 

    NSLog(@"Reachable"); 
    return YES; 

} 

no devolvió cada vez a pesar de estar conectado? No puedo entender por qué ...

¿Alguna idea? Gracias.

En una nota al margen, ¿alguien puede recomendar una buena clase de Singleton de accesibilidad limpia?

Respuesta

30

EDITADO: debe quitar el protocolo, http de su llamada reachabilityWithHostName, por lo informado a

Reachability *reachability = [Reachability reachabilityWithHostname:@"www.google.com"]; 
NetworkStatus netStatus = [reachability currentReachabilityStatus]; 
+1

Yeh ya he hecho eso y tener los bits de notificación de multa de trabajo. Quiero un método que verifique el estado de accesibilidad antes de realizar ciertas tareas (como descargar productos de compra desde la aplicación) –

+0

@AdamWaite, lo siento, cometí un error antes. He actualizado la pregunta –

+0

. Excelente, eso funcionó. Gracias. –

1

utilizo KSReachability. Funciona con NSNotification, bloques, KVO y con o sin ARC.

KSReachability *reachability = [KSReachability reachabilityToHost:@"www.google.com"]; 
reachability.onReachabilityChanged = ^(KSReachability* reachability) { 
    NSLog(@"Update: network is %@", reachability.reachable ? @"up." : @"down."); 
}; 
1

Si usted está tratando de ver si el dispositivo puede llegar a la Internet en general que es mejor usar reachabilityForInternetConnection en lugar de reachabilityWithHostName :. Además, ambas llamadas tomarán un poco de tiempo para iniciarse (todavía estará en milisegundos, pero más tiempo que el necesario para alcanzar la condición if en la línea siguiente.) Aquí hay un ejemplo de una clase singleton que usa accesibilidad.

static NetworkManager* sharedInstance = nil; 

@interface NetworkManager() 
@property (nonatomic, strong) Reachability* reachability; 
@end 

@implementation NetworkManager 
@synthesize reachability; 

+ (NetworkManager*)sharedInstance 
{ 
    @synchronized(self) { 
     if (sharedInstance == nil) { 
      sharedInstance = [[NetworkManager alloc] init]; 
     } 
    } 
    return sharedInstance; 
} 

- (id)init 
{ 
    reachability = [WYReachability reachabilityForInternetConnection]; 
} 

- (BOOL)isNetworkReachable 
{ 
    return ([self.reachability currentReachabilityStatus] != NotReachable); 
} 
@end 

Para comprobar la red alcanzable en otras clases que puede utilizar.

[[NetworkManager sharedInstance] isNetworkReachable]; 
5

Usa este código para comprobar si el dispositivo está conectado a Internet o no

uso este código en viewDidLoad:

Reachability* internetReachable; = [Reachability reachabilityForInternetConnection]; 
    [internetReachable startNotifier]; 

    hostReachable = [Reachability reachabilityWithHostName: @"www.apple.com"] ; 
    [hostReachable startNotifier]; 

y añadir esta función a su código:

-(void) checkNetworkStatus:(NSNotification *)notice 
{ 
    recheabilityBool=FALSE; 
    nonrecheabilityBool=FALSE; 
    // called after network status changes 
    NetworkStatus internetStatus = [internetReachable currentReachabilityStatus]; 
    switch (internetStatus) 
    { 
     case NotReachable: 
     { 
      nonrecheabilityBool=TRUE; 
      internetCon=0; 
      //NSLog(@"The internet is down."); 


      break; 
     } 
     case ReachableViaWiFi: 
     { 
      NSUserDefaults *prefs = [NSUserDefaults standardUserDefaults]; 
      internetCon=404; 
      [prefs setInteger:internetCon forKey:@"conKey"]; 

      //NSLog(@"The internet is working via WIFI."); 
      break; 

     } 
     case ReachableViaWWAN: 
     { 
      //NSLog(@"The internet is working via WWAN."); 

      break; 
     } 
    } 

    NetworkStatus hostStatus = [hostReachable currentReachabilityStatus]; 
    switch (hostStatus) 
    { 
     case NotReachable: 
     { 
      internetCon=0; 
      if(nonrecheabilityBool==FALSE) 
      { 
       //NSLog(@"A gateway to the host server is down."); 
      } 
      break; 

     } 
     case ReachableViaWiFi: 
     { 
      if(recheabilityBool==FALSE) 
      { 

       recheabilityBool=TRUE; 

       NSUserDefaults *prefs = [NSUserDefaults standardUserDefaults]; 
       internetCon=404; 
       [prefs setInteger:internetCon forKey:@"conKey"]; 


       //NSLog(@"The internet is working via WIFI."); 
       break; 
      } 


      //NSLog(@"A gateway to the host server is working via WIFI."); 

      break; 
     } 
     case ReachableViaWWAN: 
     { 
      //NSLog(@"A gateway to the host server is working via WWAN."); 
      break; 
     } 
    } 
} 


- (BOOL)connected 
{ 
    Reachability *reachability = [Reachability reachabilityForInternetConnection]; 
    NetworkStatus networkStatus = [reachability currentReachabilityStatus]; 
    return !(networkStatus == NotReachable); 
} 
2

Tengo un problema similar con el alcance de Tony Million: el estado de la red siempre se estableció en No tRealizable que fijarlo con la adición de la SystemConfiguration Marco

creo que sirve

+0

Esto ayuda a resolver mi caso, pero esto se debe poner en el comentario – Raptor

0

Otra respuesta completa:

-(BOOL) isReachable:(NSString *)url 
{ 
    //Retrieve the host name by given url address. 
    NSString *hostName = [[NSURL URLWithString:url] host]; 
    Reachability *r = [Reachability reachabilityWithHostName:hostName]; 

    if(NotReachable == [r currentReachabilityStatus]) { 
     NSLog(@"Not Reachable"); 
     return NO; 
    } 
    NSLog(@"Reachable"); 
    return YES; 
} 
+0

Está funcionando bien en la primera vez. Necesito comprobar la accesibilidad del host en cada acción. Pero, siempre regresa a través de Wifi. No es el anfitrión alcanzable o no. –

+0

según el archivo de clase de Reachbilty de Apple, 'Alcance no puede decirle a tu aplicación si puedes conectarte a un host en particular, solo que hay una interfaz disponible que podría permitir una conexión, y si esa interfaz es WWAN. [Alcance de Apple] (https://developer.apple.com/library/content/samplecode/Reachability/Introduction/Intro.html#//apple_ref/doc/uid/DTS40007324-Intro-DontLinkElementID_2) –

Cuestiones relacionadas