我正在使用WatchConnectivity
将一组字符串值从iPhone发送到Watch,但是这样做会出现以下错误。
无法将“__NSCFArray”类型的值(0x591244)转换为“NSString” (0x9f7458)。
我在将字典中的字符串数组发送到手表然后保存数组以在WKInterfaceTable
中使用时遇到了一些麻烦。
有人知道我哪里出错了,以及如何在手表上显示阵列?
iPhone
从手表收到第一条消息发送数据后,iPhone didRecieveMessage
执行以下操作。
有一个名为objectsArray
的数组,每个对象都有一个名为title
的字符串属性。我为所有title
值创建了一个新数组,并使用字典中的数组发送到手表。
func session(session: WCSession, didReceiveMessage message: [String : AnyObject], replyHandler: ([String : AnyObject]) -> Void) {
var watchArray = [""]
for object in self.objectsArray {
watchArray.append(object.title)
}
print("Received message from watch and sent array. \(watchArray)")
//send a reply
replyHandler( [ "Value" : [watchArray] ] )
}
观看
var objectTitlesArray = ["String"]
//Display Array in WKInterfaceTable
func loadTableData() {
table.setNumberOfRows(self.tasks.count, withRowType: "CellRow")
if self.tasks.count > 0 {
for (index, objectTitle) in self.objectTitlesArray.enumerate() {
let row = self.table.rowControllerAtIndex(index) as! CellRowController
row.tableCellLabel.setText(objectTitle)
}
}
}
//Saving the Array
func session(session: WCSession, didReceiveMessage message: [String : AnyObject], replyHandler: ([String : AnyObject]) -> Void) {
let value = message["Value"] as! [String]
dispatch_async(dispatch_get_main_queue()) {
self.objectTitlesArray = value
print("Received Array and refresh table")
loadTableData()
}
//send a reply
replyHandler(["Value":"Yes"])
}
更新
在将标签文本设置为值时,提到的错误似乎与刷新操作有关。但是在对这些行进行注释之后,该数组似乎仍未显示在WKInterfaceTable中,并且没有任何print语句输出到控制台。
答案 0 :(得分:0)
这是发生错误的地方:
let value = message["Value"] as! [String]
在上文中,您在Value
字典中获取了message
属性,并明确地将其转换为String
。它应该如下:
if let value = message["Value"] {
dispatch_async(dispatch_get_main_queue()) {
self.objectTitlesArray = value as! [String]
}
}
顺便说一下,看起来你还要将字符串数组包在另一个冗余数组中:
replyHandler( [ "Value" : [watchArray] ] )
如果您只想发送字符串数组,那么以下内容就足够了:
replyHandler( [ "Value" : watchArray ] )
答案 1 :(得分:0)
sendMessage
方法应该处理来自手机的回复。如果iPhone不使用didRecieveMessage
方法,他们没有理由在手表上使用sendMessage
方法。
@IBAction func fetchData() {
let messageToSend = ["Value":"Hello iPhone"]
session.sendMessage(messageToSend, replyHandler: { replyMessage in
if let value = replyMessage["Value"] {
self.objectTitlesArray = value as! [String]
self.loadTableData()
}
}, errorHandler: {error in
// catch any errors here
print(error)
})
}