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

kjmcneish

  • 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() {
super.init()
// Load data and initialize properties
       
 NSNotificationCenter.defaultCenter().addObserver(
self, selector: "onDeactivate", name:
"NSExtensionHostWillResignActiveNotification",
object: nil)
 
 NSNotificationCenter.defaultCenter().addObserver(
self, selector: "onBackground", name: "NSExtensionHostDidEnterBackgroundNotification",
object: nil)

 NSNotificationCenter.defaultCenter().addObserver(
self, selector: "onForeground", name: "NSExtensionHostWillEnterForegroundNotification",
object: nil)

 NSNotificationCenter.defaultCenter().addObserver(
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: https://itunes.apple.com/us/book/learn-to-code-in-swift/id942956811?mt=11