Search code examples
objective-cencodingwatchkitwatchos-2watchconnectivity

Passing NSArray of custom objects as NSData via WatchConnectivity's sendMessageData


Once a WKInterfaceController's didAppear function is fired, I send an empty NSData to WCSession's default session with the sendMessageData callback function:

// WKInterfaceController

NSData *emptyData = [[NSData alloc] init];
[[WCSession defaultSession] sendMessageData:emptyData replyHandler:^(NSData *replyMessageData) {
    NSArray *array = [NSKeyedUnarchiver unarchiveObjectWithData:replyMessageData];
} errorHandler:^(NSError *error) {
    NSLog(@"WATCH: Error from replyData %@", error);
}];

The emptyData NSData object is sent because sendMessageData: is a non-null argument. I only use it to be able to fire WCSession's Delegate method, didReceiveMessageData on the iOS app. Then the replyHandler in that very function sends the appropriate data back to the replyHandler to the WKInterfaceController.

// UITableViewController

- (void)session:(WCSession *)session didReceiveMessageData:(NSData *)messageData replyHandler:(void (^)(NSData * _Nonnull))replyHandler
{
    [self loadData:nil onSuccess:^(NSArray *tips) {
        NSData *data = [NSKeyedArchiver archivedDataWithRootObject:tips];
        replyHandler(data);
    }];
}

The problem I'm having is that I get a crash on the following line in the WKInterfaceController

NSArray *array = [NSKeyedUnarchiver unarchiveObjectWithData:replyMessageData];

Here's the error I get:

* Terminating app due to uncaught exception 'NSInvalidUnarchiveOperationException', reason: '* -[NSKeyedUnarchiver decodeObjectForKey:]: cannot decode object of class (Tip) for key (NS.objects); the class may be defined in source code or a library that is not linked'

What I've found so far:

Sorry for the long post but I've tried everything to find a solution to this problem, without success. Hope this helps more people that are having issues with WatchConnectivity Framework.


Solution

  • I solved this temporarily by using didReceiveMessage (the NSDictionary version instead of the NSData).

    I sent a manually created NSDictionary of a single NSArray that held regular NSStrings of my previous custom objects.