Dimitri T Dimitri T - 2 years ago 134
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]


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(), {

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 {

Answer Source

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"]
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download