如何打印从手表连接即时消息返回的数组

how to print array returned from watch connectivity instant message

我的 Iphone 正在发送一个数组作为手表连接消息。如何打印手表收到的数组?当我尝试打印数组时收到 'nil'。

当我在 phone 上打印发送的手表消息数组时,它 returns: ["message1": ["username": "Guest User", "titleItem": "Hillary ad Mirrors"]],

我在 phone 上发送消息的代码是:

func sendMessage() {

    var messageDataArray1 = ["username":"Guest User",  "titleItem":titleItem!]

    // Send message
    if (WCSession.defaultSession().reachable) {
        print("sending watch message array:")

        var message1 = ["message1":messageDataArray1]

        print(message1)

        WCSession.defaultSession().sendMessage(message1,
                                               replyHandler: { (reply) -> Void in
                                                dispatch_async(dispatch_get_main_queue(), {
                                                    print("received return watch msg")
                                                })
            },
                                               errorHandler: { (error) -> Void in
                                                dispatch_async(dispatch_get_main_queue(), {
                                                    //self.receivedMessageLabel.setText("error")
                                                })
            }
        )       
    }
}

我在手表接收控制器上的代码是:

// MARK: - WCSessionDelegate
func session(session: WCSession, didReceiveMessage message: [String : AnyObject], replyHandler: ([String : AnyObject]) -> Void) {
    print("received Imessage from ph")
    if let msg = message["message1"] as? String {
        print(msg)
    }
}

message["message1"] 会给你 messageDataArray1 这是一个 [String:String] 类型的字典,但是你试图将它转换为 String 这将总是失败并且 return nil.

您应该将其转换为 [String:String]

if let userData = message["message1"] as? [String:String] {
    let username = userData["username"]
    print(username) //output: "Guest User"

    let titleItem = userData["titleItem"]
    print(titleItem)
}