2012-10-01 26 views
19

he estado probando manera diferente para poner en práctica la posibilidad de conocer si el dispositivo de conseguir Internet espalda cuando la aplicación es en el fondo lo que la primera prueba de código que era el código de Apple muestra de accesibilidad http://developer.apple.com/library/ios/#samplecode/Reachability/Introduction/Intro.htmlDetectar si se pueden alcanzar en el fondo

Pero este código no notifica el estado de Internet cuando la aplicación está en segundo plano. Así que he intentado también el código folowing y que funcione cuando la aplicación se inicia desde el estado Antecedentes de primer plano (el mismo que Apple código de ejemplo de accesibilidad)

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions { 


// check for internet connection 
[[NSNotificationCenter defaultCenter] addObserver:self 
             selector:@selector(checkNetworkStatus:) 
              name:kReachabilityChangedNotification object:nil]; 

// Set up Reachability 
internetReachable = [[Reachability reachabilityForInternetConnection] retain]; 
[internetReachable startNotifier]; 

... 
} 


- (void)applicationDidEnterBackground:(UIApplication *)application { 

// check for internet connection 
[[NSNotificationCenter defaultCenter] addObserver:self 
             selector:@selector(checkNetworkStatus:) 
              name:kReachabilityChangedNotification object:nil]; 

// Set up Reachability 
internetReachable = [[Reachability reachabilityForInternetConnection] retain]; 
[internetReachable startNotifier]; 

} 



- (void)checkNetworkStatus:(NSNotification *)notice { 
// called after network status changes 

NetworkStatus internetStatus = [internetReachable currentReachabilityStatus]; 
switch (internetStatus) 
{ 
    case NotReachable: 
    { 
     NSLog(@"The internet is down."); 
     break; 
    } 
    case ReachableViaWiFi: 
    { 
     NSLog(@"The internet is working via WIFI"); 

     //Alert sound in Background when App have internet again 
     UILocalNotification *notification = [[[UILocalNotification alloc] init] autorelease]; 
     if (notification) { 
      [notification setFireDate:[NSDate date]]; 
      [notification setTimeZone:[NSTimeZone defaultTimeZone]]; 
      [notification setRepeatInterval:0]; 
      [notification setSoundName:@"alarmsound.caf"]; 
      [notification setAlertBody:@"Send notification internet back"]; 
      [[UIApplication sharedApplication] scheduleLocalNotification:notification]; 
     } 


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


     //Alert sound in Background when App have internet again 
     UILocalNotification *notification = [[[UILocalNotification alloc] init] autorelease]; 
     if (notification) { 
      [notification setFireDate:[NSDate date]]; 
      [notification setTimeZone:[NSTimeZone defaultTimeZone]]; 
      [notification setRepeatInterval:0]; 
      [notification setSoundName:@"alarmsound.caf"]; 
      [notification setAlertBody:@"Send notification internet back"]; 
      [[UIApplication sharedApplication] scheduleLocalNotification:notification]; 
     } 

     break; 
    } 
} 
} 

Mi pregunta es:¿Cuál es el camino para ser notificado cuando internet estado cambiado cuando la aplicación está en segundo plano?

Respuesta

2

No creo que haya una forma de recibir notificaciones de accesibilidad mientras está en segundo plano. La forma correcta de manejar esto sería verificar la accesibilidad en la aplicación AppDelegate - (void) applicationWillEnterForeground: (UIApplication *).

El único evento de fondo al que reaccionan las aplicaciones en segundo plano es la recepción de notificaciones push, y eso se debe a que el SO las despierta para hacerlo, y solo cuando el usuario lo solicita.

-2

Tu aplicación debe ser multitarea (VoIP, UBICACIÓN o Audio). Y de esta manera, puedes ver cómo cambia la red cuando la aplicación está en segundo plano.

+1

Hola, primero debe tener en cuenta que Apple es muy estricto sobre qué tipos de aplicaciones podrán realizar ejecuciones en segundo plano. Pls eche un vistazo a este documento de Apple. https://developer.apple.com/library/ios/documentation/iPhone/Conceptual/iPhoneOSProgrammingGuide/BackgroundExecution/BackgroundExecution.html. Además, los pls intentan explicar qué está intentando hacer tu aplicación. Tal vez podamos ofrecer un mejor enfoque! –

7

vivo no se puede cambiar si la conexión de red cambia, la mejor se puede hacer para que sea trabajo es utilizar el modo de Background FetchCapabilities. Firstable es necesario comprobar la casilla de verificación para el modo de fondo: enter image description here

Luego hay que pedir intervalo de tiempo tan a menudo como se puede cuanto antes mejor, así que sugiero application:didFinishLaunchingWithOptions: y hay que poner esta línea:

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions { 
    [application setMinimumBackgroundFetchInterval:UIApplicationBackgroundFetchIntervalMinimum]; 
    return YES; 
} 

El UIApplicationBackgroundFetchIntervalMinimum que es tan a menudo como sea posible, pero no es número exacto de segundos entre las recuperaciones de los documentos:

El más pequeño se ha podido recuperar int erval compatible con el sistema.

Y luego, cuando se dispara buscar a fondo se puede comprobar en AppDelegate con el método:

-(void)application:(UIApplication *)application performFetchWithCompletionHandler:(void (^)(UIBackgroundFetchResult))completionHandler{ 
    Reachability *reachability = [Reachability reachabilityForInternetConnection]; 
    [reachability startNotifier]; 
    NetworkStatus status = [reachability currentReachabilityStatus]; 

    switch (status) { 
     case NotReachable: { 
      NSLog(@"no internet connection"); 
      break; 
     } 
     case ReachableViaWiFi: { 
      NSLog(@"wifi"); 
      break; 
     } 
     case ReachableViaWWAN: { 
      NSLog(@"cellurar"); 
      break; 
     } 
    } 
    completionHandler(YES); 
} 

Todo esto va a trabajar en iOS 7.0 o superior.

+0

Lo he implementado como se explicó ... pero aun así realizo las llamadas de FetchWithCompletionHandler y no pude verificar la accesibilidad. – CKT

Cuestiones relacionadas