Search code examples
iosswiftwatchkitwatchconnectivitywcsession

Sending a huge dictionary via sendMessage - WatchKit


My goal is to send a huge dictionary (containing about 10 arrays) from the iOS app to the watchKit app, but I'm not getting any output on the watchKit's end.

If I send a string, the following example works fine:

let message = [ "fromParent": "some string" ]
session.sendMessage(message, replyHandler: { replyDict in }, errorHandler: { error in })

but when I try to send a dictionary, I'm not getting any output at all:

let message = [ "fromParent": dictionary ]
session.sendMessage(message, replyHandler: { replyDict in }, errorHandler: { error in })

This is how I print out the output on the watchKit's end:

func session(session: WCSession, didReceiveMessage message: [String: AnyObject], replyHandler: [String: AnyObject] -> Void) {
guard let parentMessage = message["fromParent"] as? String else { return }
print(parentMessage)
}

Solution

  • I cannot transfer (>100kb) the large dictionary via sendMessage (just relatively small ones)

    The PayloadTooLarge error was already mentioned.

    If you implement a proper error handler, you will see that the sendMessage fails because you exceeded the amount of data you could send in a message.

    session.sendMessage(message, replyHandler: nil, errorHandler: { (error) -> Void in
        print("sendMessage failed with error \(error)")
    })
    

    Alternative approaches:

    It's impractical to send such large amounts of data, and subject the user to long load times.

    • If possible, you should bundle any preloaded/static data in the watch bundle so it doesn't need to be transferred in the first place.

    • If there's no other way around needing to transfer such large amounts of data between the phone and watch, you'll need to use transferFile:metadata: (which is only subject to remaining space limits on the watch).