You can create a delegate class that listens for new data and then informs all interested interface controllers about the new data. If you have multiple interface controllers that need to be updated when new data arrives you can implement this delegate as singleton to be able to add observers from any part of your extension (like Apple does with its NSNotificationCenter class):
class SessionDelegate {
static let sharedDelegate = SessionDelegate()
private override init() {}
....
}
Define a observer protocol that all interested interface controllers can implement:
protocol DataObserver {
func dataDidChange(data: AnyObject)
}
Add an observer array to your delegate class and two methods to add and remove observers:
private var observers = [DataObserver]()
func addObserver(observer: DataObserver) {
// add the observer to observers
}
func removeObserver(observer: DataObserver) {
// remove the observer from observers
}
When you receive new data iterate through the observers and call the method defined in the protocol:
func didReceiveData(data: AnyObject) {
for observer in observers {
observer.dataDidChange(data)
}
}
Now all WKInterfaceController
classes that need to refresh can add themselves as observers:
SessionDelegate.sharedDelegate.addObserver(self)
And implement the method from the protocol:
func dataDidChange(data: AnyObject) {
// update UI
}
Finally you have to inform your delegate class that new data has arrived, so that it can inform its observers. So implement didReceiveApplicationContext
in your ExtensionDelegate
and call dataDidChange
on your delegate class:
extension ExtensionDelegate: WCSessionDelegate {
func session(session: WCSession, didReceiveApplicationContext applicationContext: [String : AnyObject]) {
SessionDelegate.sharedDelegate.dataDidChange(applicationContext)
}
}