Search code examples
iosiphone-x

applicationDidBecomeActive firing on deactivation on iPhone X


Is anyone else having trouble with applicationDidBecomeActive incorrectly firing on deactivation of the app on the new iPhone X?

Here's my test app:

class ViewController: UIViewController {

    required init?(coder aDecoder: NSCoder) {
        super.init(coder:aDecoder)
        NotificationCenter.default.addObserver(
            self,
            selector: #selector(fired),
            name: .UIApplicationDidBecomeActive,
            object: nil
        )
    }

    @objc func fired(_:Any) {
        print("fired")
    }

}

Run the app on the iPhone X simulator. Naturally, I see "fired" in the console. So far, so good. Now swipe the home indicator sideways or up, to switch to a different app or to bring up the app switcher. I see "fired" appear again in the console!

This seems just wrong, and is throwing all of my apps into a kerfuffle. How can I cope with getting an activation notification on deactivation?


Solution

  • In fact there are three notifications fired in rapid succession when the application is deactivated in the iPhone X Simulator:

    1. UIApplicationWillResignActive
    2. UIApplicationDidBecomeActive
    3. UIApplicationWillResignActive

    This is wrong (and you might want to file a bug report), but it is something that could happen if a user deactivates - activates – deactivates the app quickly, so the app should cope with that situation anyway.

    Both notifications must be handled in a symmetric fashion (and they come properly balanced, even with that bug): Actions done on "activate" must be reversed on "deactivate".