2012-10-01 9 views
19

Ho testato modo diverso per implementare la possibilità di sapere se il dispositivo di avere internet indietro quando l'applicazione è in background in modo che il primo test codice che è stato il codice di esempio raggiungibilità di Apple http://developer.apple.com/library/ios/#samplecode/Reachability/Introduction/Intro.htmlRilevare la raggiungibilità in background

Ma questo codice non notifica lo stato di Internet quando l'App è in background. Così ho provato anche il codice folowing e funziona quando App viene lanciato dallo stato di sfondo a primo piano (lo stesso di Apple codice di esempio raggiungibilità)

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

La mia domanda è:Qual è il modo per essere avvisato quando internet stato modificato quando l'app è in background?

risposta

2

Non credo che ci sia un modo per ricevere notifiche di raggiungibilità mentre sei in background. Il modo corretto per gestirlo sarebbe quello di verificare la raggiungibilità dell'applicazione AppDelegate - (void) applicationWillEnterForeground: (UIApplication *).

L'unico evento in background a cui le app in background reagiscono è la ricezione di notifiche push, e questo perché il sistema operativo si sveglia e così solo quando l'utente lo richiede.

-2

L'app deve essere multitasking (VoIP, POSIZIONE o Audio). E in questo modo, puoi prendere la rete cambiando quando l'app in background.

+1

Ciao, per prima cosa dovresti notare che Apple è molto severa su quali tipi di app saranno in grado di eseguire esecuzioni in background. Dai un'occhiata a questo documento di Apple. https://developer.apple.com/library/ios/documentation/iPhone/Conceptual/iPhoneOSProgrammingGuide/BackgroundExecution/BackgroundExecution.html. inoltre, pls prova a spiegare cosa sta cercando di fare la tua app. Forse possiamo offrire un approccio migliore! –

7

diretta non si può cambiare se la connessione di rete è cambiato, il meglio si può fare per rendere il lavoro è quello di utilizzare la modalità Background Fetch da Capabilities. Firstable è necessario controllare la casella di controllo per la modalità di sfondo: enter image description here

Allora avete bisogno di chiedere per l'intervallo di tempo tutte le volte che è possibile il più presto possibile in modo che io suggerisco application:didFinishLaunchingWithOptions: ed è necessario mettere questa riga:

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

Il UIApplicationBackgroundFetchIntervalMinimum è il più spesso possibile, ma non è esatto numero di secondi tra recuperi dalla documentazione:

Il più piccolo a prendere int erval supportato dal sistema.

E poi quando sfondo recuperare sparerà è possibile controllare in AppDelegate con metodo:

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

Tutto questo funzionerà in iOS 7.0 o superiore.

+0

Ho implementato come spiegato .. ma eseguo ancora FetchWithCompletionHandler non chiama e non è in grado di verificare la raggiungibilità. – CKT

Problemi correlati