Dimitri T Dimitri T - 1 month ago 17
Swift Question

how to print array returned from watch connectivity instant message

My Iphone is sending an array as a watch connectivity message. How do I print the array received on the watch? I am receiving 'nil' when I try print the array.

When I print the watch message array I'm sending, on the phone, it returns:
["message1": ["username": "Guest User", "titleItem": "Hillary ad Mirrors"]],

My code on the phone to send the message is:

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


my code on the watch receiving controller is:

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

Answer

message["message1"] will give you messageDataArray1 which is a dictionary of type [String:String], but you're trying to cast it as String which will always fail and return nil.

You should cast it as [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)
}
Comments