When to call activateSession() on WCSession object

懵懂的女人 提交于 2019-12-12 11:35:49

问题


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?


回答1:


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.



来源:https://stackoverflow.com/questions/33168416/when-to-call-activatesession-on-wcsession-object

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!