何时在WCSession对象上调用activateSession() [英] When to call activateSession() on WCSession object

查看:270
本文介绍了何时在WCSession对象上调用activateSession()的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想知道在手表和iOS设备上的WCSession对象上什么时候调用activateSession().

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

在文档中说:

在调用任何与会话相关的方法之前,始终分配一个委托并激活您的会话.发送消息或获取有关连接状态的信息之前,必须先配置和激活会话.

一开始我以为我的代码初始化了会话:

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

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

在iOS设备上的 viewDidLoad 中,以及在手表侧的 willActivate 中.

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?

推荐答案

WCSession代码放入viewDidLoadwillActivate时,不仅在打开应用程序时调用,而且每次在视图控制器上调用包含显示的代码.所以那不是一个理想的地方.

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.

放置此代码的最佳位置是应用程序AppDelegate中的application:didFinishLaunchingWithOptions和手表扩展程序ExtensionDelegate

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

您可以按照出色的教程的建议,将所有会话处理都放到一个单例类中. a>通过 @NatashaTheRobot .

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.

编辑

ccjensen 在他的评论中指出,如果您正在使用连接进行并发症 >,通知概览更新,您必须使用ExtensionDelegate的init方法激活会话.在这种情况下,不会调用applicationDidFinishLaunching.

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.

这篇关于何时在WCSession对象上调用activateSession()的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆