Skip to content

Instantly share code, notes, and snippets.

@bwhiteley
Last active August 29, 2015 14:12
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save bwhiteley/bc008127bd5fae9cbf5a to your computer and use it in GitHub Desktop.
Save bwhiteley/bc008127bd5fae9cbf5a to your computer and use it in GitHub Desktop.
Ensure UI updates to WatchKit Interface Controller only happen while the controller is active.
/*
"WatchKit ignores attempts to set values of interface objects
while your interface is inactive.... Modifications can be made
only during initialization of your interface controller and
between calls to willActivate and [didDeactivate]."
*/
class MyWKInterfaceController: WKInterfaceController {
private var isActive:Bool = true
private var uiUpdateQ:Array<() -> ()> = []
// Perform any UI updates that may be taking
// place when the controller is inactive
// self.updateUI { /* update UI elements */ }
func updateUI(updates:() -> ()) {
if self.isActive {
if !NSThread.isMainThread() {
dispatch_async(dispatch_get_main_queue()) {
self.updateUI(updates)
}
}
else {
updates()
}
}
else {
self.uiUpdateQ.extend([updates])
}
}
override func willActivate() {
super.willActivate()
self.isActive = true
for updates in self.uiUpdateQ {
updates()
}
self.uiUpdateQ = []
}
override func didDeactivate() {
super.didDeactivate()
self.isActive = false
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment