When to call activateSession() on WCSession object
Asked Answered
D

1

5

I wonder at what point one would call activateSession() on a WCSession object on the watch and on the iOS device.

In the documentation it says:

Always assign a delegate and activate your session before calling any session-related methods. The session must be configured and activated before sending messages or obtaining information about the state of the connection.

At first thought I put my code to initialise the session:

 if (WCSession.isSupported()) {
        session = WCSession.defaultSession()
        session.delegate = self
        session.activateSession()
    }

in viewDidLoad on the iOS device and in willActivate on the watch side.

It works... but I don't think it's a good solution. I'm not too familiar with the app-lifecycle yet but as far as I understand those are called every time the app's are opened.

Does that result in a "reconnect" every time one of the apps is opened?

Where would be a good place to place that code?

Debbiedebbra answered 16/10, 2015 at 10:37 Comment(0)
L
11

When you put the WCSession code in viewDidLoad and willActivate it is not only called when the app is opened but every time the view controller that contains the code is shown. So that is not an ideal place.

The best place to put this code is in application:didFinishLaunchingWithOptions in your app's AppDelegate and in applicationDidFinishLaunching in your watch extensions's ExtensionDelegate

You can put all the session handling into a singleton class, as suggested in this great tutorial by @NatashaTheRobot.

That way the session is only created once for the time the app in being held in memory.

EDIT

As ccjensen pointed out in his comment, if you are using the connection for a Complication, Notification or Glance update you have to activate the session in the ExtensionDelegate's init method. applicationDidFinishLaunching will not be called in those cases.

Levorotation answered 16/10, 2015 at 11:58 Comment(2)
actually the ExtensionDelegate's applicationDidFinishLaunching is only called when the WatchKit app is being launched. It will not get called when the extension is being launched for a complication, notification or glance update. The ExtensionDelegate's init method is a better place as it will be called in all these other situations.Hilel
Oh, yes you are totally right! Thanks for pointing that out, I wasn't thinking that far. I updated my answer.Levorotation

© 2022 - 2024 — McMap. All rights reserved.