-1

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

无法将“__NSCFArray”(0x591244)类型的值转换为“NSString”(0x9f7458)。

我在将字典中的字符串数组发送到手表然后保存数组以在WKInterfaceTable.

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

苹果手机

在收到手表发送数据的第一条消息后,iPhonedidRecieveMessage会执行以下操作。

有一个名为的数组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 中,并且没有任何打印语句输出到控制台。

4

2 回答 2

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 ] )

于 2016-03-16T13:30:54.663 回答
0

sendMessage方法应该处理来自电话的回复。didRecieveMessage如果 iPhone 不使用方法,他们也没有理由在手表上使用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)
    })

}
于 2016-03-17T13:36:17.303 回答