Uso de métodos de fondo / primer plano en AppDelegate


Estoy planeando implementar multi-tarea en mi aplicación. Puedo ver muchos métodos aquí para hacer eso en el AppDelegate como applicationWillResignActive, applicationDidEnterBackground, applicationWillEnterForeground, ...

Pero.... No veo la forma en que deberían usarse, ni por qué no están en ViewController... Ni para qué están aquí.

Quiero decir : cuando la aplicación entra en segundo plano, no se en qué vista está mi usuario. Y de vuelta, cuando la aplicación entra en primer plano, ¿cómo sabría qué hacer y qué puedo llamar, para actualizar la vista, por ejemplo ?

Habría entendido si esos métodos estuvieran en cada controlador de vista, pero aquí, no veo para qué se pueden usar de una manera concreta...

¿Puedes ayudarme a entender la manera de implementar las cosas en esos métodos ?

Author: Bakuriu, 2011-01-31

2 answers

Cada objeto recibe una notificación UIApplicationDidEnterBackgroundNotification cuando la aplicación se pone en segundo plano. Así que para ejecutar algún código cuando la aplicación se pone en segundo plano, solo tienes que escuchar esa notificación donde quieras:

[[NSNotificationCenter defaultCenter] addObserver:self
                                         selector:@selector(appHasGoneInBackground:)
                                             name:UIApplicationDidEnterBackgroundNotification
                                           object:nil];

No olvides liberar el oyente cuando ya no necesites escucharlo:

[[NSNotificationCenter defaultCenter] removeObserver:self];

Y lo mejor de lo mejor, puedes jugar de la misma manera con las siguientes notificaciones :

  • UIApplicationDidEnterBackgroundNotification
  • UIApplicationWillEnterForegroundNotification
  • UIApplicationWillResignActiveNotification
  • UIApplicationDidBecomeActiveNotification
 130
Author: Oliver,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2018-08-21 13:50:08

No están en ninguno de sus controladores de vista porque iOS adopta un patrón de diseño 'delegado', donde puede estar seguro de que un método se disparará sobre una clase (en este caso, el Delegado de la aplicación para su aplicación) cuando sea necesario.

Como proceso de aprendizaje, ¿por qué no pones los NSLog en esos métodos para ver cuándo son despedidos?

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

    // Override point for customization after application launch.
    NSLog(@"didFinishLaunchingWithOptions");
    [self.window makeKeyAndVisible];

    return YES;
}


- (void)applicationWillResignActive:(UIApplication *)application 
{
    /*
     Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
     Use this method to pause ongoing tasks, disable timers, and throttle down OpenGL ES frame rates. Games should use this method to pause the game.
     */
    NSLog(@"applicationWillResignActive");
}


- (void)applicationDidEnterBackground:(UIApplication *)application 
{
    /*
     Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later. 
     If your application supports background execution, called instead of applicationWillTerminate: when the user quits.
     */
    NSLog(@"applicationDidEnterBackground");
}


- (void)applicationWillEnterForeground:(UIApplication *)application 
{
    /*
     Called as part of  transition from the background to the active state: here you can undo many of the changes made on entering the background.
     */
    NSLog(@"applicationWillEnterForeground");
}


- (void)applicationDidBecomeActive:(UIApplication *)application 
{
    /*
     Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
     */
    NSLog(@"applicationDidBecomeActive");
}


- (void)applicationWillTerminate:(UIApplication *)application 
{
    /*
     Called when the application is about to terminate.
     See also applicationDidEnterBackground:.
     */
    NSLog(@"applicationWillTerminate");
}
 8
Author: Alan Zeino,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2017-11-26 11:01:12