Passing Data From A Class To WatchOS 2 (Connectivity)

Deadly 提交于 2019-12-10 11:40:08

问题


I'm hoping someone here may have some thoughts on Watch OS 2 connectivity that can point me in the right direction. Succinctly, I am trying to pass a set of data (from a custom class called FileData) to my WatchKit extension. When I run the WatchKit app, I can see that the WCSession is being activated, but the dataset never seems to get passed to the Watch (though if I change the data to a String and pass something simple like "hello", it does work properly);

TableViewController.swift (iOS side)

...
func sendToWatch(files: [FileData]) {
    let session = WCSession.defaultSession()
    let applicationData = ["myFiles":[FileData](files)]
    session.sendMessage(applicationData, replyHandler: { reply in
        print("Got reply: \(reply)")
    }, errorHandler: { error in
        print("error: \(error)")
    })
}
...

InterfaceController.swift (WatchKit extension)

...
func session(session: WCSession, didReceiveMessage message: [String : AnyObject]) {
    let files = message["myFiles"] as! [FileData]
    print("Got a message")
        dispatch_async(dispatch_get_main_queue(), { () -> Void in
            print(files)
        })

    reloadTable()
}
...

Am I wrong in assuming that I can pass a custom class via Watch Connectivity? Or have I done something wrong here?

Thank you!


回答1:


Yes, that is an incorrect assumption. The WCSession sendMessage documentation states that the dictionary may only contain property list types which are basic types such as strings, integers, floats, data, etc. So to send your content, either convert the object to a dictionary of key-value pairs or use the less recommended approach of using NSKeyedArchiver to convert your object directly to data.



来源:https://stackoverflow.com/questions/31920373/passing-data-from-a-class-to-watchos-2-connectivity

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!