Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

When to call activateSession() on WCSession object

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?

like image 913
David Schmoecker Avatar asked Oct 16 '15 10:10

David Schmoecker


1 Answers

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.

like image 111
joern Avatar answered Nov 05 '22 19:11

joern