Reputation: 6381
I try to do something when the home button and power button has been clicked. I am developing in iOS.
This is the code I use:
- (void)viewDidDisappear:(BOOL)animated{
[super viewDidDisappear:animated];
NSLog(@"viewDidDisappear");
}
- (void)viewWillDisappear:(BOOL)animated{
[super viewWillDisappear:animated];
NSLog(@"viewWillDisappear");
}
- (void)applicationFinishedRestoringState{
NSLog(@"applicationFinishedRestoringState");
}
Why is the above function not being called when I click the power button or home button on the iPhone?
Did I miss something?
Upvotes: 0
Views: 2248
Reputation: 9356
According to Apple's documentation
This method is called before the receiver’s view is about to be added to a view hierarchy and before any animations are configured for showing the view. You can override this method to perform custom tasks associated with displaying the view. For example, you might use this method to change the orientation or style of the status bar to coordinate with the orientation or style of the view being presented. If you override this method, you must call super at some point in your implementation.
To get notified, when your application resumes you should use:
- (void)applicationDidBecomeActive:(UIApplication *)application
This method is implemented in your AppDelegate.m
On the other hand
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 add some stuff in your method
-(void)screenLocked{
//do stuff
}
Upvotes: 1
Reputation: 1837
viewDidDisappear:
and viewWillDisappear:
will get called if the view is pushed or popped or in anyway gets disappeared in your own runloop, going to background by pressing home or power button doesn't count as view' related events, but rather app related events. you should register for UIApplicationWillResignActiveNotification
notification instead.
e.g.
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(disappearSelector) name:UIApplicationWillResignActiveNotification object:nil];
Upvotes: 1