How to send Array to Watch using sendMessage | Error: Could not cast value of type '__NSCFArray' to 'NSString'

How to send Array to Watch using sendMessage | Error: Could not cast value of type '__NSCFArray' to 'NSString'

我正在使用 WatchConnectivity 将字符串值数组从 iPhone 发送到手表,但是这样做时出现以下错误。

Could not cast value of type '__NSCFArray' (0x591244) to 'NSString' (0x9f7458).

我在将字典中的字符串数组发送到手表然后保存数组以在 WKInterfaceTable 中使用时遇到了一些小问题。

有谁知道我哪里出错了以及如何在手表上显示数组?

iPhone

收到手表发送数据的第一条消息后,iPhones 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 中,打印语句的 none 被输出到控制台。

这是错误发生的地方:

let value = message["Value"] as! [String]

在上面,您在 message 字典中得到 Value 属性 并且显式转换为 String。应该是这样的:

if let value = message["Value"] {

    dispatch_async(dispatch_get_main_queue()) {
        self.objectTitlesArray = value as! [String]
    }
}

顺便说一句,您似乎也在将字符串数组包装在另一个冗余数组中:

replyHandler( [ "Value" : [watchArray] ] )

如果您只想发送字符串数组,那么以下内容就足够了:

replyHandler( [ "Value" : watchArray ] )

sendMessage 方法应该处理来自 phone 的回复。如果 iPhone 不使用 sendMessage 方法,他们就没有理由在手表上使用 didRecieveMessage 方法。

@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)
    })

}