接收applicationContext并避免重新传输的正确方法? - WatchConnectivity

时间:2017-12-27 09:28:30

标签: ios swift watchkit applicationcontext watchconnectivity

我一直在努力从我的iOS应用程序向我的WatchOS发送一个Applications undefined表单。

int notificationCount

问题是,只要notifyCount发生变化,上面的代码片段就会做出反应。这意味着当我打开我需要notificationCount的InterfaceController时,在从iOS对应的值更新之前,我没有任何数字。

我怀疑只有当发送值不相同时才func session(_ session: WCSession, didReceiveApplicationContext applicationContext: [String : Any]) {}。但有没有一种正确的方法来检查notificationCount的值是否具有与最近传输相同的值以避免一些重新传输?

1 个答案:

答案 0 :(得分:0)

只需将notificationCount保存在Extension Delegate的属性(或您可能用于存储数据的任何其他实例)中,并在控制器的唤醒方法中使用(或/和/并在适当时激活)。此外,您可能希望将其保存在UserDefaults或文件中,以便重新启动应用程序。

这样的事情:

class ExtensionDelegate: NSObject, WKExtensionDelegate, WCSessionDelegate {
    var notificationCount: Int?

    // ...

    func applicationDidFinishLaunching() {
        // do your normal init stuff
        // read notificationCount from UserDefaults
    }

    // ...

    func session(_ session: WCSession, didReceiveApplicationContext applicationContext: [String : Any]) {
        if let count = applicationContext["NotificationCount"] {
            notificationCount = count
            // save to UserDefaults here
        }
    }
}