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.
Asked
Active
Viewed 242 times
2

AST
- 211
- 6
- 18

Accid Bright
- 592
- 5
- 17
2 Answers
4
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.

Andrew
- 3,166
- 21
- 32
-
These are also called when your widget scrolls offscreen or the user locks the screen or switches from Today to Notifications. I don't know any way to specifically detect that the notification center was closed. – Christopher Pickslay Jul 30 '15 at 21:34
3
@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
}
})
}

Christopher Pickslay
- 17,523
- 6
- 79
- 92
-
-
The main disadvantage of this method is that it's available since iOS 8.2. – Accid Bright Aug 05 '15 at 07:29