Использование методов фона / переднего плана в AppDelegate

Я планирую реализовать многозадачность в моем приложении. Я вижу много методов здесь, чтобы сделать это в AppDelegate лайк applicationWillResignActive, applicationDidEnterBackground, applicationWillEnterForeground...

Но... я не вижу, как их следует использовать, и почему их нет в ViewControllers... Ни для чего они здесь.

Я имею в виду: когда приложение входит в фоновом режиме, я не знаю, на каком экране находится мой пользователь. И обратно, когда приложение выходит на передний план, как я узнаю, что делать и что я могу назвать, например, для обновления представления?

Я бы понял, если бы эти методы были в каждом контроллере вида, но здесь я не вижу, для чего они могут быть использованы конкретным образом...

Можете ли вы помочь мне понять, как реализовать эти методы?

2 ответа

Решение

Каждый объект получает UIApplicationDidEnterBackgroundNotification уведомление, когда приложение выходит в фоновом режиме. Итак, чтобы запустить некоторый код, когда приложение работает в фоновом режиме, вам просто нужно прослушать это уведомление, где вы хотите:

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

Не забудьте освободить слушателя, когда вам больше не нужно его слушать:

[[NSNotificationCenter defaultCenter] removeObserver:self];

И лучшие из лучших, вы можете играть так же со следующими уведомлениями:

  • UIApplicationDidEnterBackgroundNotification
  • UIApplicationWillEnterForegroundNotification
  • UIApplicationWillResignActiveNotification
  • UIApplicationDidBecomeActiveNotification

Их нет ни в одном из ваших контроллеров представления, потому что iOS принимает шаблон проектирования "делегат", где вы можете быть уверены, что метод сработает в классе (в данном случае, делегат приложения для вашего приложения) при необходимости.

В качестве учебного процесса, почему бы вам не включить NSLog в эти методы, чтобы увидеть, когда их уволят?

- (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");
}
Другие вопросы по тегам