Suggestions

close search

Back to Text Chat Overview

Text Chat Step 1: Adding text chat

The code for this section is in the signaling branch of the learning-opentok-ios repo:

git checkout signaling

This page shows the difference between this branch and the basics branch which it was built upon.

The signaling branch adds the following functionality:

When the user enters text in the text chat input text field, the [self sendChatMessage:] method is called:

- (void) sendChatMessage
{
    OTError* error = nil;
    [_session signalWithType:@"chat"
                      string:_chatInputTextField.text
                  connection:nil error:&error];
    if (error) {
        NSLog(@"Signal error: %@", error);
    } else {
        NSLog(@"Signal sent: %@", _chatInputTextField.text);
    }
    _chatTextInputView.text = @"";
}

This method calls the [OTSession signalWithType:string:connection:] method. This method sends a message to clients connected to the OpenTok session. Each signal is defined by a type string identifying the type of message (in this case "chat") and a string containing the message.

When another client connected to the session (in this app, there is only one) sends a message, the implementation of the [OTSessionDelegate session:receivedSignalType:fromConnection:withString:] method is called:

- (void)session:(OTSession*)session receivedSignalType:(NSString*)type fromConnection:(OTConnection*)connection withString:(NSString*)string {
    NSLog(@"Received signal %@", string);
    Boolean fromSelf = NO;
    if ([connection.connectionId isEqualToString:session.connection.connectionId]) {
        fromSelf = YES;
    }
    [self logSignalString:string fromSelf:fromSelf];
}

This method checks to see if the signal was sent by the local iOS client or by the other client connected to the session:

Boolean fromSelf = NO;
if ([connection.connectionId isEqualToString:session.connection.connectionId]) {
    fromSelf = YES;
}

The session argument represents your clients OTSession object. The OTSession object has a connection property with a connectionId property. The connection argument represents the connection of client sending the message. If these match, the signal was sent by the local iOS app.

The method calls the [self logSignalString:] method which displays the message string in the text view for chat messages received.

This app uses the OpenTok signaling API to implement text chat. However, you can use the signaling API to send messages to other clients (individually or collectively) connected to the session.