0

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?

Sebastian Simon
  • 18,263
  • 7
  • 55
  • 75
Wun
  • 6,211
  • 11
  • 56
  • 101

2 Answers2

1

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];
M. Porooshani
  • 1,797
  • 5
  • 34
  • 42
1

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
}
iAnurag
  • 9,286
  • 3
  • 31
  • 48
  • `UIApplicationDidEnterBackgroundNotification` will get called when OS decided that app should actually go to background, it might not get called at all if user returns to app shortly, on the other hand `UIApplicationWillResignActiveNotification` will get called when the app resigns being the front app and will always get called upon Home or power button press. – M. Porooshani Aug 25 '15 at 07:48