Search code examples
objective-ccocoa-touchnsnotifications

How to simulate applicationWillResignActive message?


How can one simulate applicationWillResignActive to be called?

Locking screen, going to main menu, simulating phone call - none seemed to have helped.

In case I expect things that won't happen, let me tell you more: I subscribe to this message and when that happens hope that notification is sent to a method as listed below:

UIApplication *app = [UIApplication sharedApplication];

[[NSNotificationCenter defaultCenter] addObserver:self 
                 selector:@selector(applicationWillResignActive:) 
                 name: UIApplicationWillResignActiveNotification object:app];

Solution

  • Your code is valid, it works for me. And locking the screen or hitting the home button will cause this notification to be posted.

    *(One caveat to this is if your device does not support multitasking or if you have the "Application does not run in background" property set to yes in your *info.plist. In which case it will go straight to the "UIApplicationWillTerminateNotification" notification)

    So barring that there there are two possiblities:

    1) Your addObserver code is not being called, ie. It's in the wrong method.

    To test try this:

    UIApplication *app = [UIApplication sharedApplication];
    [[NSNotificationCenter defaultCenter] addObserver:self 
                                             selector:@selector(applicationWillResignActive:) 
                                                 name:UIApplicationWillResignActiveNotification 
                                               object:app];
    NSLog(@"Observer added");
    

    2) The observer method is not being called properly. Which requires the same method as the at selector.

    To test try this:

    -(void)applicationWillResignActive:(NSNotification *)notification{
        NSLog(@"applicationWillResignActive");
    }
    
    • Just as an additional point, if you want to see in action which of these notifications are called and when. In your AppDelegate class put the line NSLog(@"%@", NSStringFromSelector(_cmd)); in each of the -application... methods and it will log them when they are called. It's a nice hands on way to get to know them.