Quick follow up of my previous article about integrating React-Native in iMessage Apps

Once the integration is done properly the next step is to be able to interact with the new iMessage APIs to be able to send messages properly.

Sending

So what I do is, I created an Manager class for that, as I didn’t want to expose functions directly on the MessagesViewController. I wanted the MessagesViewController to be about initialization and lifecycle only.

Now, to send messages you need access to the conversation. So, whenever there is a new conversation I pass it to the Manager class.

The code to send a message is fairly simple.

// This is inside the Manager class // This has to be initialized and updated by MessagesViewController

MSConversation* conv; RCT_EXPORT_METHOD(createMessage:(NSDictionary*) dict

resolve:(RCTPromiseResolveBlock)resolve

reject:(RCTPromiseRejectBlock)reject) { // Download the image or use a default one

NSString* imgURLStr = dict[@"imgUrl"];

UIImage* image;

if (imgURLStr && [imgURLStr length] != 0) {

NSURL* imgURL = [NSURL URLWithString:imgURLStr];

image = [UIImage imageWithData:[NSData dataWithContentsOfURL:imgURL]];

} else {

image = [UIImage imageNamed:@"defaultMessageImage"];

} MSMessageTemplateLayout* layout = [MSMessageTemplateLayout new];

layout.image = image;

layout.caption = dict[@"caption"];

layout.subcaption = dict[@"subcaption"];

MSSession* session = conv.selectedMessage.session ?: [MSSession new];

NSURLComponents* components = [NSURLComponents componentsWithString:@"

components.queryItems = @[

// Anything you want to pass here

[NSURLQueryItem queryItemWithName:@"caption" value:dict[@"caption"]],

];

NSURL* URL = components.URL; // If we already have a session use it, else create a new one.MSSession* session = conv.selectedMessage.session ?: [MSSession new];NSURLComponents* components = [NSURLComponents componentsWithString:@" http://example.com "];components.queryItems = @[// Anything you want to pass here[NSURLQueryItem queryItemWithName:@"caption" value:dict[@"caption"]],];NSURL* URL = components.URL; MSMessage* message = [[MSMessage alloc] initWithSession:session];

message.layout = layout;

message.URL = URL; [conv insertMessage:message completionHandler:^(NSError* err) {

if (err) {

reject(@"createMessage", err.localizedDescription, err);

} else {

resolve(nil);

// This line is used to go from expanded view to compact view,

// so that the user can see there is a message to be sent.

[viewController dismiss];

}

}];

}

Of course you can pass what you want in the dictionary and customize the layout more. I added an example on how to download a picture from Internet and how to create a URL with query parameters.

Receiving

When you receive a message, you need a function to parse the query parameters so you can load them in React-Native. Here is what I use to parse the parameters: