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.
Asked
Active
Viewed 1,676 times
3

zk_mars
- 1,339
- 2
- 15
- 36

Matt Logan
- 5,886
- 5
- 31
- 48
-
The phone call hold button? – Carl Veazey Aug 14 '13 at 21:24
-
What is this 'hold button' you speak of? – hgwhittle Aug 14 '13 at 21:26
-
The button on the top right of the phone. – Matt Logan Aug 14 '13 at 21:26
-
1My mistake -- the "lock" button – Matt Logan Aug 14 '13 at 21:27
-
Please edit your question with 'lock' instead of 'hold' – hgwhittle Aug 14 '13 at 21:28
-
possible duplicate of [iOS: Check if the Phone is Locked](http://stackoverflow.com/questions/7969252/ios-check-if-the-phone-is-locked) – rob mayoff Aug 14 '13 at 21:28
-
See also [this answer](http://stackoverflow.com/a/14213968/77567). – rob mayoff Aug 14 '13 at 21:40
2 Answers
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