Is it possible to determine when iOS widget hides?

259 views Asked by At

Is there any way to catch the moment when a user hides the notification panel with a widget? I want to save some information into the database at that moment (I want it to be similar to applicationDidEnterBackground:). Any other ideas about how to save data at the last moment would also be appreciated.

2

There are 2 answers

1
Andrew On BEST ANSWER

Usually, your widget would be a UIViewController instance, conforming to the NCWidgetProviding protocol. That means, that you can take advantage of UIViewController's functionality and execute your code in

- (void)viewWillDisappear:(BOOL)animated;

or

- (void)viewDidDisappear:(BOOL)animated;

I tested it and it worked.

2
Christopher Pickslay On

@Andrew is correct that the normal UIViewController lifecycle methods will be called when your widget goes off screen, but your controller will also be deallocated shortly thereafter, and its process suspended. So if you need to do some I/O, you have no guarantee it will complete.

The recommended way to keep your extension's process alive is to request a task assertion using performExpiringActivityWithReason:usingBlock:.

override func viewWillDisappear(animated: Bool) {
    super.viewWillDisappear(animated)
    NSProcessInfo.processInfo().performExpiringActivityWithReason("because", usingBlock: { (expired) -> Void in
        if expired {
            NSLog("expired")
        } else {
            // save state off to database
        }
    })
}