Last active
August 29, 2015 14:12
-
-
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.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/* | |
"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