MatterGoal
MatterGoal

Reputation: 16430

Using singleton WCSession delegate instead of instance methods

I'm experiencing a strange issue with WatchOS (but I suppose that this problem is similar with iOS and OSX).

I'm using a singleton to handle a WCSession delegate (The full code is by NatashaTheRobot, I paste here only a portion of her code, the full code is here ). This class has a startSession function where the singleton is associated as delegate of the session:

func startSession() {
    session?.delegate = self
    session?.activateSession()
}

and all the delegate functions are defined inside the same class, like session:didReceiveMessage:replyHandler:

I'd like to be able to have the delegate called every time that the Watch app receives a message independently by the current InterfaceController.

I thought that a good place to achieve this goal might be the ExtensionDelegate class:

class ExtensionDelegate: NSObject, WKExtensionDelegate {

    let session = WatchSessionManager.sharedManager // THE SINGLETON INSTANCE

    func applicationDidFinishLaunching() {
        session.startSession()
    }

it seems that this code is not working and the delegate function are never called.

Then I decided to go for a less generic way and I started adding the reference to the singleton instance inside all the InterfaceController... but again it doesn't work and delegate methods are never been called. Then, in my last attempt, I've implemented the session delegate protocol directly inside the InterfaceController code. In that case I receive the messages from the iOS app... it was working correctly (obviously only when the watch app is presenting that specific InterfaceController).

My question are: why implementing a generic singleton object doesn't work? Why I have to implement the delegate directly on the InterfaceController to make it work?

Upvotes: 2

Views: 607

Answers (1)

ccjensen
ccjensen

Reputation: 4656

Try moving the startSession call from the ExtensionController's applicationDidFinishLaunching to its init method. The init gets called no matter which context (complication, app, glance, notification, etc) the extension is being loaded for.

Upvotes: 1

Related Questions