Skip to content

Messaging Service

Li Lin edited this page Nov 19, 2018 · 33 revisions

StraaS Messaging SDK provides basic feature to interact with StraaS Messaging Service.
You can read Messaging Service Concept to get the basic idea of messaging service.

Use StraaSMessagingSDK

Initialize Chatroom Manager

  • After successfully configured application, create an STSChatManager instance directly.

    STSChatManager * manager = [STSChatManager new];
  • STSChatManager supports multi-connection. You can create manager once and use it to manage all chat rooms in the app.

  • STSChatManager instance methods execute asynchronously. Delegate method or handler block will be called when operation completed.

  • STSChatManager support connect to personal chat & connect with data channel.

  • User identity

Join Chatroom

To connect to a chatroom, we needs to know the following properties.

NSString * JWT; //To identify user identity, @"" means you will connect to a chatroom with Guest identity. 
NSString * chatroomName; // The chatroomName you want to connect.
STSChatroomConnectionOptions connectionOptions; // The connectionOptions you want to connect.
// and then set JWT & chatroomName & connectionOptions before connect to chat room

Before calling other messaging API, you should connect to a chatroom or other api would return STSMSGErrorCodeChannelNotConnected error.

[manager connectToChatroom:chatroomName JWT:JWT options:self.connectionOptions eventDelegate:self];

// If connect to chatroom success, STSChatManager would notify delegate by calling `chatroomConnected:`
- (void)chatroomConnected:(STSChat *)chatroom {
  //chatroom has connected.
}
// If not connect success, STSChatManager would notify delegate by calling `chatroom:failToConnect`
- (void)chatroom:(STSChat *)chatroom failToConnect:(NSError *)error {
  //failed to connect chatroom.
}

Retrieve STSChat/STSChatUser object

// STSChatManager will need the STSChat object to do other command. This is the way to get the STSChat object you want.

- (BOOL)isPersonalChat {
    return connectionOptions & STSChatroomConnectionIsPersonalChat;
}

//This method would return the chat with chatroomName and isPersonalChat or not.
- (STSChat *)chat {
    return [self.manager chatForChatroomName:chatroomName isPersonalChat:self.isPersonalChat];
}

//This method would return the user who use the `JWT` to connect to the chat.
- (STSChatUser *)chatUser {
    return [self.manager currentUserForChatroom:self.chat];
}

//call `self.chat` will return the STSChat object that you connected before.

Change or remove event delegate

// set or remove event delegate using `setEventDelegate:forChatRoom:`
[manager setEventDelegate:nil forChatroom:self.chat];

Leave Chat Room

[manager disconnectFromChatroom:self.chat];

// If success to disconnect from chat, STSChatManager would notify delegate by calling chatRoomDisconnected:
- (void)chatroomDisconnected:(STSChat *)chatroom {
    // connection with chat room was closed
}

List Users

NSArray * usersInChat;
[manager getUsersForChatroom:self.chat userType:STSGetUsersTypeOnlineUsers success:^(NSArray<STSChatUser *> * users) {
    usersInChat = users;
} failure:^(NSError * error) {
    // error handling
}];

Load Messages

NSArray * chatMessages;
[manager getMessagesForChatroom:self.chat configuration:nil success:^(NSArray<STSChatMessage *> * messages) {
    //messages would be page 1 with default 10 message items.
    chatMessages = messages;
} failure:^(NSError * error) {
    // error handling
}];

//If you want to custom get messages for chatroom, you can use STSGetMessagesConfiguration to fulfill, for example:
STSGetMessagesConfiguration * messagesConfiguration = [STSGetMessagesConfiguration new];
messagesConfiguration.page = 2;
messagesConfiguration.perPage = 50;
[manager getMessagesForChatroom:self.chat configuration:messagesConfiguration success:^(NSArray<STSChatMessage *> * messages) {
    //messages would be page 2 with 50 message items if the chat contains so many messages.
    chatMessages = messages;
} failure:^(NSError * error) {
    // error handling
}];

Update guest nickname

Try to update a member user name will end with failure.

[manager updateGuestNickname:@"A girl has no name" chatroom:self.chat success:^() {
    // update success, next `chatroom:usersUpdated:` delegate method call should reflect this change
} failure:^(NSError * error) {
    // error handling
}];

// STSChatManager also notify delegate `chatroom:usersUpdated:` if user update successfully.
- (void)chatroom:(STSChat *)chatroom usersUpdated:(NSArray<STSChatUser *> *)users {
  //users contain the one who is just updated their nickname.
}

Post Message

Beware of cooldown of the chat room. Try to send message during before cooldown reset will end with failure.

if ([manager cooldownForChatroom:self.chat] == 0) {
    [manager sendMessage:@"Valar Morghulis" chatroom:self.chat success:^() {
        // message sent, `chatroom:messageAdded:` delegate method should be called right after.
    } failure:^(NSError * error) {
        // error handling
    }];
}

// STSChatManager would notify delegate `chatroom:messageAdded:` if message sent successfully.
- (void)chatroom:(nonnull STSChat *)chatroom messageAdded:(nonnull STSChatMessage *)message {
    // new message arrived
}

Data channel

Data channels are designed to send custom data, and to keep them separated from chat messages.

There are two methods to send custom data:

You can send aggregated data with key by calling sendAggregatedDataWithKey:chatroom:success:failure:. This method would aggregate your key into STSAggregateItems.

[manager sendAggregatedDataWithKey:@"Apple" chatroom:self.chat success:^{
    //Aggregated data sent successfully.
} failure:^(NSError * _Nonnull error) {
    //Aggregated data sent unsuccessfully.
}];

// STSChatManager would notify delegate `chatroom:messageAdded:` if aggregated data sent successfully.
- (void)chatroom:(STSChat *)chatroom aggregatedDataAdded:(NSArray<STSAggregatedData *> *)aggregatedData {
  //aggregateData would an array of STSAggregatedData objects.
}

You can send rawData by calling sendRawData:chatroom:success:failure:. RawData should be a valid JSON object only, like NSDictionary or NSArray.

[self.manager sendRawData:@{@"StraaS":@"is your choice",
                            @"I have a pen": @"I have an apple",
                            @"array": @[@"ab", @"cd"]}
                 chatroom:self.chat 
  success:^{
    //raw data sent successfully.
} failure:^(NSError * _Nonnull error) {
    //raw data sent unsuccessfully.
}];

// STSChatManager would notify delegate `chatroom:rawDataAdded:` if raw data sent successfully.
- (void)chatroom:(STSChat *)chatroom rawDataAdded:(STSChatMessage *)rawData {
  //The value property of `rawData` would just like the raw data you sent.
}

Pin message

  • Require v0.10.11 or later.
NSString * messageId = "<#THE_ID_OF_A_MESSAGE_WHICH_BELONGS_TO_THE_CHATROOM#>";
[manager pinMessage:messageId chatroom:self.chat success:^{
} failure:^(NSError * error) {
  // error handling
}];

Unpin message

  • Require v0.10.11 or later.
[manager unpinMessageFromChatroom:self.chat success:^{
} failure:^(NSError * error) {
  // error handling
}];