ios - WatchConnectivity - 使用 sendMessage

标签 ios watchkit watchos-2

我正在尝试使用 Swift 中的 WatchConnectivity API 在 Apple Watch(版本 2.0.1)和我的 iPhone(运行 iOS 9.1)之间建立连接。

我关注了this tutorial并且无法实现设备之间的消息传递。

来自 Apple Watch 的消息:

    let applicationData = ["data":sampleData]

    self.wcSession.sendMessage(applicationData, replyHandler: {(_: [String : AnyObject]) -> Void in
        // handle reply from iPhone app here
        }, errorHandler: {(error ) -> Void in
            // catch any errors here
    })

在我的 ViewController.swift 中:

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

    let sample:HKQuantitySample = (message["data"] as? HKQuantitySample)!
    print("Sample messaged: \(sample)")
}

func sessionReachabilityDidChange(session: WCSession) {
    print("session reachability changed: \(session.reachable)")
}

Watch 应用程序和 iOS 应用程序都在前台!! 我不确定缺少什么。

最佳答案

所有采用字典作为参数的 WCSession API 只接受 property list types 的字典;这包括 sendMessage API您正在使用:

message / A dictionary of property list values that you want to send. You define the contents of the dictionary that your counterpart supports. This parameter must not be nil.

所以 HKSamples 不是 property list type这就是为什么这不起作用,尽管您说错误处理程序没有被调用,这听起来非常可疑。您确定将代码更改为此不会记录任何内容吗?

self.wcSession.sendMessage(applicationData, replyHandler: {(_: [String : AnyObject]) -> Void in
    // handle reply from iPhone app here
    }, errorHandler: {(error ) -> Void in
        print(error);
})

关于ios - WatchConnectivity - 使用 sendMessage,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34051505/

相关文章:

swift - watch 操作系统 : getting applicationDidBecomeActive notifications

swift - 标签上的 Apple Watch 文字

iOS swift : Update navigation button with "Back" text

当用户在“系统设置”->“显示和亮度”上启用 "Bold Text"时,iOS 应用程序会在启动屏幕上卡住

ios - 错误 ITMS-90363 : "Invalid Info.plist key. The key ' CFBundleIcons~ipad' in bundle MyApp. 应用程序……

swift - 如何将后台应用程序刷新添加到 swift WatchOs 应用程序

swift - 禁用 WatchKit TableRow 的选择

ios - 错误: Page Control jump twice with single page swap

ios - SourceKitService 已终止,没有 Xcode 警告或错误

ios - 无法在真正的 Apple Watch 上构建 hello world 应用程序