即使应用程序在后台,手表应用程序也可以接收背景信息吗?

Osk*_*ård 7 ios watchkit watchos

我不知道如何updateApplicationContext在手表应用程序被前景化之前让数据到达手表。它似乎仅在手表应用程序处于前台时才有效。

手表如何在后台接收文件?

这就是我一直在努力实现的目标:

IOS代码:

func sendDataToWatch() {
        if WCSession.isSupported() {
            do {
                try WCSession.default.updateApplicationContext(["key":value])
            } catch {
                print("ERROR: \(error)")
            }
        }
    }
Run Code Online (Sandbox Code Playgroud)

观看代码:

func session(_ session: WCSession, didReceiveApplicationContext
        applicationContext:[String : Any]) {

      //handle data when it arrives

    }
Run Code Online (Sandbox Code Playgroud)

我注意到 WatchConnectivity 提供了一个处理函数。这是我应该设置的东西,以便能够在 Watch App 处于后台运行或什至未启动时处理后台连接?

func handle(_ backgroundTasks: Set<WKRefreshBackgroundTask>) {
    // Sent when the system needs to launch the application in the background to process tasks. Tasks arrive in a set, so loop through and process each one.
    for task in backgroundTasks {
        // Use a switch statement to check the task type
        switch task {
        case let backgroundTask as WKApplicationRefreshBackgroundTask:
            // Be sure to complete the background task once you’re done.
            backgroundTask.setTaskCompletedWithSnapshot(false)
        default:
            // make sure to complete unhandled task types
            task.setTaskCompletedWithSnapshot(false)
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

iOS*_*per 1

根据苹果公司的说法,当会话可达时,您可以使用 SendMessage 将数据从 iPhone 发送到 Apple Watch。

https://developer.apple.com/documentation/watchconnectivity/wcsession/1615687-sendmessage

当 WatchKit 扩展处于活动状态并运行时,从该扩展调用此方法会唤醒后台相应的 iOS 应用程序并使其可访问。

您可以使用以下方法将数据从 iPhone 发送到 Apple Watch

斯威夫特2.2

let msg = ["IPrequest":"IsLogin"]

WCSession.defaultSession().sendMessage(msg, replyHandler: { (replyDict) in
    print(replyDict)
    }, errorHandler: { (error) in
        print(error)
})
Run Code Online (Sandbox Code Playgroud)

使用以下方法收到字典

斯威夫特2.2

func session(session: WCSession, didReceiveMessage message: [String : AnyObject], replyHandler: ([String : AnyObject]) -> Void)
{

    dispatch_async(dispatch_get_main_queue()) { () -> Void in

        print("Response:\(message)")

    }
}
Run Code Online (Sandbox Code Playgroud)

我已经在我的一个项目中实现了上述解决方案。

希望对您有帮助!