3

Is there an available view controller method that is called when the user presses the lock button? I'm looking for something like viewDidDisappear: or viewWillDisappear:, but specific to the case of the lock button being pressed.

zk_mars
  • 1,339
  • 2
  • 15
  • 36
Matt Logan
  • 5,886
  • 5
  • 31
  • 48

2 Answers2

2

A notification called UIApplicationDidEnterBackgroundNotification is posted when the user locks their phone. Here's how to listen for it:

In viewDidLoad: of your ViewController:

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

Then, define a method (mine was called screenLocked above) and write code you want to be executed when the screen is locked.

-(void)screenLocked{
    //do stuff
}

Also, to do some necessary cleanup, add this method to your ViewController too.

-(void)dealloc{
    [[NSNotificationCenter defaultCenter] removeObserver:self name:UIApplicationDidEnterBackgroundNotification object:nil];
}
hgwhittle
  • 9,316
  • 6
  • 48
  • 60
1

Try this :

- (void)applicationDidEnterBackground:(UIApplication *)application
{
  UIApplicationState state = [application applicationState];
  if (state == UIApplicationStateInactive) {
      NSLog(@"Sent to background by locking screen");
  } else if (state == UIApplicationStateBackground) {
      NSLog(@"Sent to background by home button/switching to other app");
  } 
}
Samkit Jain
  • 2,523
  • 16
  • 33
  • Note that this is a method defined in the AppDelegate, and not a method of `UIViewController`. – hgwhittle Aug 14 '13 at 21:43
  • Thanks for the help. I was specifically looking for a method that would be called inside of a view controller. hw731's answer addresses this. – Matt Logan Aug 14 '13 at 21:45