Pergunta

Estou planejando implementar multitarefas em meu aplicativo. Posso ver muitos métodos aqui para fazer isso no AppDelegate, como applicationWillResignActive, applicationDidEnterBackground, applicationWillEnterForeground, ...

Mas .... Não vejo como eles devem ser usados, nem por que não estão nos ViewControllers ... Nem para que servem aqui.

Quer dizer: quando o aplicativo entra em segundo plano, não sei em qual view meu usuário está. E de volta, quando o aplicativo entrar em primeiro plano, como saberei o que fazer e o que posso chamar para atualizar a visualização, por exemplo?

Eu teria entendido se esses métodos estivessem em cada controlador de visualização, mas aqui, não vejo para que eles podem ser usados de forma concreta ...

Você pode me ajudar a entender como implementar as coisas nesses métodos?

Foi útil?

Solução

Cada objeto recebe uma notificação UIApplicationDidEnterBackgroundNotification quando o aplicativo entra em segundo plano.Portanto, para executar algum código quando o aplicativo entra em segundo plano, você apenas precisa ouvir a notificação onde quiser:

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

Não se esqueça de liberar o ouvinte quando não precisar mais ouvi-lo:

[[NSNotificationCenter defaultCenter] removeObserver:self];

E o melhor de tudo, você pode jogar da mesma forma com as seguintes notificações:

  • UIApplicationDidEnterBackgroundNotification
  • UIApplicationWillEnterForegroundNotification
  • UIApplicationWillResignActiveNotification
  • UIApplicationDidBecomeActiveNotification

Outras dicas

Eles não estão em nenhum de seus controladores de visualização porque o iOS adota um padrão de design 'delegado', onde você pode ter certeza de que um método será acionado em uma classe (neste caso, o App Delegate para seu aplicativo) quando necessário.

Como um processo de aprendizagem, por que você simplesmente não coloca NSLogs nesses métodos para ver quando eles são disparados?

- (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");
}
Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top