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.
Is it possible to determine when iOS widget hides?
259 Views Asked by Accid Bright At
2
There are 2 best solutions below
2
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
}
})
}
Usually, your widget would be a
UIViewControllerinstance, conforming to theNCWidgetProvidingprotocol. That means, that you can take advantage ofUIViewController's functionality and execute your code in- (void)viewWillDisappear:(BOOL)animated;or
I tested it and it worked.