App in foreground and background

拈花ヽ惹草 提交于 2019-12-13 03:59:10

问题


I have a button ON/OFF in my viewcontroller that plays some music when it is turned on by the user. Now if the user clicks the iPhone home button and re-launches my app again, the button is shown as "ON" but there is no music playing. So the user has to hit ON-OFF-ON again for music to start playing again.

Anyone know how can I call my ON/OFF view controller button so that I can set it to OFF when app enters background and set it to ON and play the music when it enters forground in these app delegates?

I know I need to write to a plist file the button & music state on applicationDidEnterBackground. I don't know how can I get to those action from appdelegate since they are defined in my viewcontroller.

Similary, when the app enters the foreground I will read the saved plist file and then set the state of music and button again. Again, I don’t know how to call my controller methods from delegate.

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

     NSLog(@"Inside applicationDidEnterBackground");
}

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

    NSLog(@"Inside applicationWillEnterForeground");

}

回答1:


One possible methodology is to send a message from the app delegate to the view controllers to save or restore state. Then the view controller, which have access to their internal state, can implement any needed save and restore methods.

If the app delegate does not directly contain a reference to the active view controller, it can send the message down the chain, to root view controller, which can then send a message to the next view controller, and etc., each controller saving anything it considers important on the way down.




回答2:


All you need to do is subscribe to the UIApplicationDidEnterBackgroundNotification notification in your view controller

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

Theres also a notification for DidEnterForeground too.



来源:https://stackoverflow.com/questions/8548555/app-in-foreground-and-background

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!