Author Topic: What's the best way to save and restore state in my WatchKit app  (Read 8101 times)


  • Administrator
  • *****
  • Posts: 719
    • View Profile
To provide the best user experience, you should save and restore your app’s state when your app is deactivated and activated. This allows the user to pick up where they left off.

Although Apple's documentation mentions using your interface controller's willActivate and didDeactivate methods to restore/save your app's state, these methods fire too frequently to make them a good choice. For example, when the user navigates to/from scenes in your app, the associated interface controllers' willActivate and didDeactivate methods fire.

Fortunately, , Apple has added the following notifications that alert you when an app is truly being activated and deactivated:
  • NSExtensionHostWillEnterForegroundNotification
  • NSExtensionHostDidBecomeActiveNotification
  • NSExtensionHostWillResignActiveNotification
  • NSExtensionHostDidEnterBackgroundNotification
These notifications are associated with the NSExtensionContext class. You can register for them through NSNotificationCenter in the init or awakeFromContext method of your app’s main interface controller. For example:

Code: [Select]
override init() {
// Load data and initialize properties
self, selector: "onDeactivate", name:
object: nil)
self, selector: "onBackground", name: "NSExtensionHostDidEnterBackgroundNotification",
object: nil)

self, selector: "onForeground", name: "NSExtensionHostWillEnterForegroundNotification",
object: nil)

self, selector: "onActive", name: "NSExtensionHostDidBecomeActiveNotification",
object: nil)

The NSExtensionHostWillResignActiveNotification’s handler method (onDeactivate in this example) is a great place to put code that saves your app’s state.

The WillEnterForegroundNotification’s handler method is a great place to put code that restores your app’s state.

All the best!
Kevin McNeish
Author of Learn to Code in Swift: