ios - watchOS 不能 sendMessage() 一个结构

标签 ios swift watchkit watchos

我在我的 iOS 应用程序及其 Apple Watch 扩展中都声明了这个结构

struct nonIndexStruct {
    let name: [String]
    let message: [String]
}

我创建了一个这样的对象

let nIS = nonIndexStruct(name: sortedNameArray.map({ ($0 ).name }), message: sortedNameArray.map({ ($0 ).name }))

为了将它传递给我的 Apple Watch Extension,我将对象放入字典中

let chatsMasterDict:[String: Any] = ["chatsMaster": nIS]

打印这个非常好,所有数据都在这个对象中可用。要发送它,我打电话

session.sendMessage(chatsMasterDict, replyHandler: nil, errorHandler: nil)

现在的问题是没有任何东西到达 Apple Watch 端。 errorHandler 仅在 Apple Watch App 未打开时打印一些内容。 (关于 watch a​​pp打不开)

Apple Watch 上的接收方法如下所示,它会打印接收到的所有内容 - 除了上面显示的情况外,该方法根本不会被调用。

func session(_ session: WCSession, didReceiveMessage message: [String : Any]) {
    print("didReceive")
    print (message)

    if let val = message["chatsMaster"]{
        print("chatsMaster came")
    . . .

我最好的猜测是,虽然该结构对两个系统都可用,但中间的桥梁并不“知道”它,也无法处理它。关闭应用程序时,我也会得到

Could not cast value of type '__NSCFString' (0x12e9fe0) to 'NSArray' (0x12ea670). 2017-09-06 12:23:24.237016+0200 APPNAME WatchKit Extension[20802:3718623] Could not cast value of type '__NSCFString' (0x12e9fe0) to 'NSArray' (0x12ea670).

但同样,这只会在我停止进程时发生,所以请确定这是否与我的问题有关。

编辑:Apple Watch 文档说

The keys and values of your dictionary must all be property list types, because the data must be serialized and sent wirelessly.

所以这可能就是它不起作用的原因。最好的解决方法是什么?制作 Data我想这有点矫枉过正,因为我的结构的内容非常简单:/

最佳答案

你没有收到错误真的很奇怪,但问题的核心是你正在尝试使用 sendMessage 函数发送自定义结构,该函数只能用于发送属性列表类型。

最好的解决方案是(因为您的结构非常简单并且它的所有属性都是属性列表类型)可能将您的结构转换为字典并使用 sendMessage 发送字典。

struct nonIndexStruct {
    let name: [String]
    let message: [String]

    func toDictionary()->[String:[String]]{
        var dict = [String:[String]]()
        dict["name"] = self.name
        dict["message"] = self.message
        return dict
    }
}

let chatsMasterDict = ["chatsMaster": nIS.toDictionary()]
session.sendMessage(chatsMasterDict, replyHandler: nil, errorHandler: nil)

关于ios - watchOS 不能 sendMessage() 一个结构,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46073248/

相关文章:

ios - Xcode 5新文档将注释注释与属性或方法放在同一行

ios - identifierForVendor或类似的watchOS(2.0+)

ios - 如何将所选 Collection View Cell 的图像推送到另一个 View Controller?

swift - 如何在 Swift 中从应用程序启动命令行工具?

ios - WatchKit 的 willActivate() 函数。 Xcode 不喜欢 self.view.insertSubview

ios - prepareForSegue() 不工作( swift )

swift - 以编程方式添加 AdMob 横幅

ios - 查找 WKInterfaceImage 的高度和宽度

ios - 具有WatchKit扩展名的父应用程序是否为iOS 8及更高版本?

swift - 如何使用 UI 单元测试获取嵌入式框架的 Xcode 8 代码覆盖率