Search code examples
iosobjective-cimessage-extension

Set text in Active Conversation in iMessage


I wrote some code to add text to the Messages.app input field in my iMessage extension.

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    NSLog(@"didSelect called");
    NSLog(@"%d", 1);
    [[self activeConversation] insertText:@"https://google.com" completionHandler:^(NSError * error) {
        NSLog(@"Error happened");
        NSLog(@"Error: %@", error);
    }];
    NSLog(@"%d", 2);
}

The strange part is that all of the normal logs are happening. The app will log "didSelect called", "1" and "2". However, the message - the Google url - isn't being inserted, and the error logs aren't being shown. So I don't really have a clue as to what's going wrong. Any idea's what I'm doing wrong?


Solution

  • Solution #1

    1. Send correct reference from MessagesViewController to your view controller.
    2. Check activeConversation value for nil:

    if ([self activeConversation] != nil) {
        [[self activeConversation] insertText:@"Some text" completionHandler:^(NSError * _Nullable error) {
            NSLog(@"error: %@", error.localizedDescription);
        }];
    } else {
        NSLog(@"Conversation is nil");
    }
    

    Solution #2

    1. Create Singleton in iMessage extension name space.
    2. In MessagesViewController in - (void)viewDidLoad setup reference to your MSConversation: [[Conversation shared] activeConversation] = [self activeConversation];
    3. Use [[Conversation shared] activeConversation] insertText: .... ]; for sending messages from any controllers.