0

I read in some posts to setup WCWatchConnectivity Session in delegate rather than controller. How do you transfer the data received in delegate then to the controller for further processing (in Swift)?

joern
  • 27,354
  • 7
  • 90
  • 105
TPeter
  • 463
  • 3
  • 15

1 Answers1

1

In your delegate class:

If you need to update several view controllers you could implement your delegate class as a singleton to be able to add observers from any part of your app or extension (like Apple does with its NSNotificationCenter class):

class WatchSessionDelegate {
    static let sharedDelegate = WatchSessionDelegate()
    private override init() {}
    ....
}

You can define a observer protocol:

protocol DataObserver {
    func dataDidChange(data: AnyObject)
}

Then you add an observer array to your delegate class:

private var observers = [DataObserver]()

And two methods to add and remove an observer:

func addObserver(observer: DataObserver) {
   // add the observer to observers
}

func removeObserver(observer: DataObserver) {
   // remove the observer from observers
}

Then, when the data has been received you iterate through the observers and call the method defined in the protocol:

func didReceiveData(data: AnyObject) {
    for observer in observers {
        observer.dataDidChange(data)
    }
}

In your UIViewControllers / WKInterfaceController classes:

To inform a UIViewController or WKInterfaceController about the data change, just have it conform to the DataObserver protocol and add it to the observers:

WatchSessionDelegate.sharedDelegate.addObserver(self)

And implement the method from the protocol:

func dataDidChange(data: AnyObject) {
    // update UI
}
joern
  • 27,354
  • 7
  • 90
  • 105
  • Thank you Joern. Just tried the above but get error in Complication Controller when trying to add to the observers with: 'ExtensionDelegate.sharedDelegate.addObserver(self)' stating that ExtensionDelegate has no member sharedDelegate. Am doing so in override init. – TPeter Oct 12 '15 at 23:10
  • I was assuming that you would implement your delegate as a singleton. I'll add this to my answer. – joern Oct 13 '15 at 05:50
  • Just remember not to try to initialize the delegate class via `init`. Always use `YourDelegateClass.sharedDelegate` to access the delegate class. It is initialized automatically. In fact you'll get an error if you try to call `init` on it (thats what the private init override is for) – joern Oct 13 '15 at 06:04
  • Thank you Joern! Appreciated – TPeter Oct 20 '15 at 12:07