0

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");

}
Verbeia
  • 4,400
  • 2
  • 23
  • 44
Sam B
  • 27,273
  • 15
  • 84
  • 121

2 Answers2

0

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.

hotpaw2
  • 70,107
  • 14
  • 90
  • 153
0

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.

Tony Million
  • 4,296
  • 24
  • 24