Chat APIs and In-app Messaging SDKs for Developers

Applozic provides Chat APIs and In-app Messaging SDKs for Android, iOS and Web apps to power cross-device, multi-platform rich messaging.
Find comprehensive guides and platform-specific Chat API documentation to get started with In-app Messaging.

Guides    API Explorer

iOS

Chat View Controller

Pre-built customizable chat UI - Conversation

This section would help you understand how you could initiate or launch chat in any one of the 3 formats

  1. One to One chat also called User to User chat
  2. Group Chat
  3. Contextual Chat

Before we begin, make sure you have added all the permissions as mentioned here.

Using Applozic Core SDK

Initiating Chat.

For the chat to initiate, it is necessary that ALChatManager file is added to your project.

📘

Add ALChatManager file to use the default methods

Launching Chat list Screen

A chat list screen is a list of all the chat's that a user has been a part of, a sample of the same is given below

In our case, we are looking at showing a chat list to your End user.

Implement the following code at the event or Button action designated for showing this list.

[chatManager launchChat:self];
chatManager.launchChat(self)

Launching chat - One to one and Groups

Every user and Group within Applozic is assigned a Unique Userid and Group id respectively. The following code uses this User id or Group id to launch chat between users or group of users.

Add this code to the event or Button action designated to this feature within your app.

NSString * userIdOfReceiver =  @"receiverUserId";
[chatManager launchChatForUserWithDisplayName:userIdOfReceiver 
  withGroupId:nil  //If launched for group, pass groupId(pass userId as nil)
  andwithDisplayName:nil //Not mandatory, if receiver is not already registered                                                     you should pass Displayname.
  andFromViewController:self ];
// For user
chatManager.launchChatForUser(<user_id>, fromViewController: self)
// For group
chatManager.launchChatForGroup(<group_id>, fromController: self)

Contextual Conversation

What is Contextual Conversation?

A conversation between two or more users on a particular topic, product or situation.

Applozic API's allow you to customize a chat's context, allowing developers to create and launch chat with a specific context set.

Following screenshot depicts a sample contextual conversation wherein users are chatting with each other regarding MacBook Pro

Building a Contextual Conversation

You would have to implement the following code to build a context based chat. Implement this at the event or button action in your project designated for the same.

ALConversationProxy * alConversationProxy = [[ALConversationProxy alloc] init];
alConversationProxy.topicId = @”buyMacPro";
alConversationProxy.userId = @"adarshk"

ALTopicDetail * alTopicDetail    = [[ALTopicDetail alloc] init];
alTopicDetail.title              = @”Mac Book Pro";
alTopicDetail.subtitle           = @"13’ Retina";
alTopicDetail.link = @"http://d.ibtimes.co.uk/en/full/319949/macbook-pro-13in-retina.jpg";
alTopicDetail.key1               = @"Product ID";
alTopicDetail.value1            = @"mac-pro-r-13";
alTopicDetail.key2              = @"Price”;
alTopicDetail.value2            = @"Rs.1,04,999.0";

NSData *jsonData = [NSJSONSerialization dataWithJSONObject:alTopicDetail.dictionary  
options:NSJSONWritingPrettyPrinted error:nil];
NSString *topicDetails = [[NSString alloc] initWithData:jsonData    encoding:NSUTF8StringEncoding];

alConversationProxy.topicDetailJson = topicDetails;
var alConversationProxy = ALConversationProxy()
alConversationProxy.topicId = "buyMacPro"
alConversationProxy.userId = "adarshk"

let alTopicDetail    = ALTopicDetail()
alTopicDetail.title = "Mac Book Pro"
alTopicDetail.subtitle = "13’ Retina"
alTopicDetail.link = "http://d.ibtimes.co.uk/en/full/319949/macbook-pro-13in-retina.jpg"
alTopicDetail.key1 = "Product ID"
alTopicDetail.value1 = "mac-pro-r-13"
alTopicDetail.key2 = "Price”"
alTopicDetail.value2 = @"Rs.1,04,999.0"

let jsonData = JSONSerialization.data(withJSONObject: alTopicDetail.dictionary(), options: .prettyPrinted)
let topicDetails = String(data: jsonData, encoding: .utf8)
alConversationProxy.topicDetailJson = topicDetails

ALConversationProxy is a class which let you build your conversation context

ALConversationProxy has three properties as following:

topicId: A unique ID for your Topic/context you want to chat.
userId: User ID of the receiver.
alTopicDetail: Contains the following:

  • Topic title
  • Topic subtitle
  • Image link
    key1 and value1: For example, key1 = "Product ID" and value1 = "569-01"
    key2 and value2: For example, key2 = "Price" and value2 = "Rs.1,50,00"

Key1 and Key2 is a placeholder to store with respective value1 and value2 values

Creating and Launching Contextual Chat

To create and launch Contextual Chat using ALConversationProxy object call the below method:

ALChatManager * chatManager = [[ALChatManager alloc] init];
[chatManager createAndLaunchChatWithSellerWithConversationProxy:newProxy fromViewController:self];
let chatManager = ALChatManager()
chatManager.createAndLaunchChatWith(conversationProxy: alconversationProxy, from: self)

Using ApplozicSwift SDK

Initiating Chat

For the chat to initiate, it is necessary that ALChatManager file is added to your project.

📘

Add ALChatManager file to use the default methods

Launching Chat list Screen

A chat list screen is a list of all the chat's that a user has been a part of, a sample of the same is given below

In our case, we are looking at showing a chat list to your End user.

Implement the following code at the event or Button action designated for showing this list.

chatManager.launchChatList(from: self)

Launching chat - One to one and Groups

Every user and Group within Applozic is assigned a Unique Userid and Group id respectively. The following code uses this User id or Group id to launch chat between users or group of users.

Add this code to the event or Button action designated to this feature within your app.

/// For user
chatManager.launchChatWith(contactId: <USER_ID>, from: self)

/// For group
chatManager.launchGroupWith(clientGroupId: <CLIENT_GROUP_ID>, from: self)

Creating and Launching Contextual Chat

Check this to know about contextual chat and how to build it.

To create and launch Contextual Chat using ALConversationProxy object call the below method:

/// Check above link to know about how to create conversation proxy. 
chatManager.launchChatWith(conversationProxy: newProxy, from: self)

Save Video to Gallery

If you want to save the downloaded and captured videos to the gallery(Photos album) then use the below setting to enable it:

[ALApplozicSettings enableSaveVideosToGallery:YES]
ALApplozicSettings.enableSaveVideosToGallery(flag: true)

Build your UI from scratch - Conversation

This doc will guide you on how to get the messages for the list and individual group/user messages

❗️

Setup ApplozicClient

Note: You need to setup ApplozicClient before using the methods refer to this link

Latest Message list

The latest message list is used to display the messages to the logged in user based on the communication time. This list contains only the latest messages for each user and group that the logged in user has interacted with, sorted in descending order of the communication time.

[self.applozicClient getLatestMessages:NO withCompletionHandler:^(NSMutableArray *messageList, NSError *error) {
        if(!error){
        
        }
    }];
applozicClient.getLatestMessages(false, withCompletionHandler: { messageList, error in
            if error == nil {
             
            }
        })

Pass isNextPage flag to NO or false to fetch an initial list of messages and messageList has NSMutableArray of type ALMessage object.

Handling pagination in the Latest message list

This will load next set of messages from applozic server where isNextPage will be YES or true

[self.applozicClient getLatestMessages:YES withCompletionHandler:^(NSMutableArray *messageList, NSError *error) {
        if(!error){
         
        }
    }];
applozicClient.getLatestMessages(true, withCompletionHandler: { messageList, error in
            if error == nil {
                for message: ALMessage? in messageList as? [ALMessage?] ?? [ALMessage?]() {

                }
            }
        })

Pass isNextPage flag to YES or true to fetch the next list of messages and messageList has NSMutableArray of type ALMessage object.

Message list for a particular thread

The previous section explained how to create the message list that displays the latest messages for a particular logged in user. But what happens if the user clicks on the conversation in the list? The user should see a detailed list of messages with that user/group. This section will guide you through getting messages for the individual conversation.

One-to-one chat messages

MessageListRequest *messagelistRequest = [[MessageListRequest alloc] init];
messagelistRequest.userId = @"userid"; // pass userId

if ([ALUserDefaultsHandler isServerCallDoneForMSGList:messagelistRequest.userId]) {
     [ALMessageService getMessageListForContactId:messagelistRequest.userId isGroup:NO channelKey:nil conversationId:nil startIndex:0 withCompletion:^(NSMutableArray *messageList)  {
         if (messageList.count) {
            // Get the messages
             for (ALMessage *message in messageList) {

             }
          }
    }];
} else {
  [self.applozicClient getMessages: messagelistRequest withCompletionHandler:^(NSMutableArray *messageList, NSError *error) {
       if(!error){
            // Get the messages
                     for (ALMessage *message in messageList) {

           }
        }
  }];
}
if ALUserDefaultsHandler.isServerCallDone(forMSGList: messagelistRequest.userId) {
     ALMessageService.getMessageList(forContactId: messagelistRequest.userId, isGroup: messagelistRequest.channelKey != nil, channelKey: messagelistRequest.channelKey, conversationId: nil, start: 0, withCompletion: {
          messages in
         guard let messages = messages as? [ALMessage] else {
            return
          }
           // Get the messages here 
   })
} else {
     applozicClient.getMessages(messagelistRequest, withCompletionHandler: { messageList, error in
         if error == nil {
           // Get the messages here
         }
    })
 }

Group/Channel individual messages

MessageListRequest *messagelistRequest = [[MessageListRequest alloc] init];
messagelistRequest.channelKey = groupId; // Pass groupId or channelkey here
    
if ([ALUserDefaultsHandler isServerCallDoneForMSGList:messagelistRequest.channelKey.stringValue]) {
    [ALMessageService getMessageListForContactId:messagelistRequest.userId isGroup:NO channelKey:nil conversationId:nil startIndex:0 withCompletion:^(NSMutableArray *messageList)  {
      if (messageList.count) {
         // Get the messages
         for (ALMessage *message in messageList) {

         }
      }
    }];
  } else {
     [self.applozicClient getMessages: messagelistRequest withCompletionHandler:^(NSMutableArray *messageList, NSError *error) {
            if(!error){
                // Get the messages
                for (ALMessage *message in messageList) {

                }
            }
     }];
  }
let messagelistRequest = MessageListRequest()
        messagelistRequest.channelKey = groupId // Pass groupId or channelkey here
        
if ALUserDefaultsHandler.isServerCallDone(forMSGList:  messagelistRequest.channelKey.stringValue) {
     ALMessageService.getMessageList(forContactId: messagelistRequest.userId, isGroup: messagelistRequest.channelKey != nil, channelKey: messagelistRequest.channelKey, conversationId: nil, start: 0, withCompletion: {
          messages in
            guard let messages = messages as? [ALMessage] else {
               return
           }
         // Get the messages here
    })
 } else {
   applozicClient.getMessages(messagelistRequest, withCompletionHandler: { messageList, error in
        if error == nil {
           // Get the messages here
         }
    })
 }

Handling pagination for individual messages

You can get the batch of next set of 60 messages for a particular user/group by passing the message.createdAtTime of the first top message from the messageList array.

One to one chat messages with pagination

Pass userId of the user for which you want to get the conversation messages and pass the first top message message.createdAtTime to get older messages of the user.

The below code explains handling the pagination for a particular user:

MessageListRequest *messagelistRequest = [[MessageListRequest alloc] init];
    messagelistRequest.userId = @"userid"; // Pass userId
    messagelistRequest.endTimeStamp = createdAtTime; // Pass first message message.createdAtTime

    [self.applozicClient getMessages: messagelistRequest withCompletionHandler:^(NSMutableArray *messageList, NSError *error) {
        if(!error){
            
        }
    }];
let messagelistRequest = MessageListRequest()
        messagelistRequest.userId = "userId" // pass userId
        messagelistRequest.endTimeStamp = createdAtTime
        
        applozicClient.getMessages(messagelistRequest, withCompletionHandler: { messageList, error in
            if error == nil {
                
            }
        })

Group/Channel chat messages with pagination

Pass channelKey of Channel/Group for which you want to get the conversation messages and pass the first top message message.createdAtTime to get older messages of that Channel/Group.

The below code explains handling the pagination for a particular channel/group:

MessageListRequest *messagelistRequest = [[MessageListRequest alloc] init];
    messagelistRequest.channelKey = channelKey; // Pass channelKey
    messagelistRequest.endTimeStamp = createdAtTime; // Pass first message message.createdAtTime

    [self.applozicClient getMessages: messagelistRequest withCompletionHandler:^(NSMutableArray *messageList, NSError *error) {
        if(!error){
            
        }
    }];
let messagelistRequest = MessageListRequest()
        messagelistRequest.channelKey = channelKey // Pass channelKey
        messagelistRequest.endTimeStamp = createdAtTime // Pass first message message.createdAtTime
        
        applozicClient.getMessages(messagelistRequest, withCompletionHandler: { messageList, error in
            if error == nil {
                
            }
        })

Latest messages for one to one or group chats

The latest message list is used to display the messages to the logged in user based on the communication time.
This method you can use in case if you want to show only one to one chats in one viewController or Group chats in another view controller

Only one to one or group chat latest messages

[self.applozicClient getLatestMessages:NO withOnlyGroups:NO withCompletionHandler:^(NSMutableArray *messageList, NSError *error) {

            if(error  == nil){
                 //Use the messageList    
            }

  }];
applozicClient.getLatestMessages(false, withOnlyGroups: false, withCompletionHandler: { messageList, error in

            if error == nil {
            }

   })

Pass first parameter flag to NO or false to fetch an initial list of messages.
If you want to fetch the next set of latest messages then you can pass YES or true to get messages from the server

Parameters in the above function.

Parameter

Value

Description

isNextPage

YES/NO or true or false

if NO, it will load the only latest 60 messages.
If YES it will load the next set of messages from server.

withOnlyGroups

YES/NO or true or false

if NO, it will only get the latest messages of one to one chat
If YES, it will only get the latest messages of group chats

Understanding ALMessage properties

Checking received message or sent message

In your Cell you can check if its Inbox message or received, Sent message or Outbox message as below:

if([message.type isEqualToString:@MT_INBOX_CONSTANT]){
        // Received  message 
  }else {
        // Sent message 
  }
if (message.type == "4") {
            // Received  message
        } else {
            // Sent message
        }

Checking message content type

You can check the message content types like a text message, Location message, Attachment message, Contact card message, Video message etc.

if(message.isLocationMessage){
        //Location message contentType
    }else if (message.isContactMessage){
        // Contact card attachement contentType
    }else if(alMessage.fileMeta){
        if([message.fileMeta.contentType hasPrefix:@"image"])
        {
            // Image attachemnt message contentType
      NSString *filePath =  message.imageFilePath; if its downloaded you can get the path 
        }
        else if ([message.fileMeta.contentType hasPrefix:@"video"])
        {
            // Video message contentType
        }
        else if ([message.fileMeta.contentType hasPrefix:@"audio"])
        {
            // Audio message contentType
        }
    }else if (message.contentType == ALMESSAGE_CONTENT_DEFAULT)  {
        //Message text contentType
    } else if(message.contentType == ALMESSAGE_CHANNEL_NOTIFICATION)
    {
        //Custom message like addedd,removed,created,changed name of channel
    }
if(message.isLocationMessage()){
      //Location message contentType
    }  else if(message.isContactMessage()) {
      // Contact card attachement contentType
   } else if((alMessage.fileMeta) != nil) {
            if message.fileMeta.contentType?.hasPrefix("image") ?? false {
                // Image attachemnt message contentType
                        let filePath = message.imageFilePath //if its downloaded you can get the path 
                        
            } else if message.fileMeta.contentType?.hasPrefix("video") ?? false {
                // Video message contentType
             let filePath = message.imageFilePath //if its downloaded you can get the path 
            } else if message.fileMeta.contentType?.hasPrefix("audio") ?? false {
                // Audio message contentType
                let filePath = message.imageFilePath //if its downloaded you can get the path 

            }
            
   }  else if message.contentType == ALMESSAGE_CONTENT_DEFAULT {
       // Message text contentType
    }

📘

NOTE:

There is no separate contentType for Image, video, audio etc it will come under message.isDocumentMessage() then you need to check if its image or video or audio message.

To get the message text from ALMessage

message.message

Checking one to one or channel/group chat message

In conversation list to know whether its a channel/group chat message or one to one chat:

if ([message getGroupId]) {
     //Its a channel/group chat  message       
  } else {
     message.to;  // one to one message 
  }
if message.groupId != nil {
     //Its a channel/group chat  message
   } else {
       message.to // one to one message
   }

📘

Note: You can get the details(like display name, image URL etc.) of message sender using loadContactByKey API as described below.

Checking group/channel or one to one chat and getting details of channel or user

You can check its a channel or one to one chat and get the details contact or channel object from message

ALContactDBService *theContactDBService = [[ALContactDBService alloc] init];
    ALChannelService *channelService = [[ALChannelService alloc] init];
    
    if (message.groupId) {
        ALChannel *channel =   [channelService getChannelByKey:message.groupId];
        
    } else {
        ALContact *contact = [theContactDBService loadContactByKey:@"userId" value: alMessage.to];
      
    }
let channelService = ALChannelService()
let contactService  = ALContactService()

    if (message.groupId != nil) {
           let channel =  channelService.getChannelByKey(message.groupId) as ALChannel
            
        } else {
            let contact =  contactService.loadContact(byKey: "userId", value: message.to) as ALContact
        }

Checking status of the message

For checking the status of the message sent to the server, Delivered to the user, Delivered and read the message.

Use below code to check the status

switch (message.status.intValue) {
            case DELIVERED_AND_READ :
            {
                //Sent message update the ui with read tick
            }
            break;
                
            case DELIVERED:
            {
                //Sent message update the UI with Deliverd tick
            }
            break;
          
            case SENT:
            {
                //Sent message update the UI with sent tick
            }
            break;
          
            default:
            break;
 }
switch message.status {
        case DELIVERED_AND_READ:
        //Sent message update the ui with read tick
        case DELIVERED:
        //Sent message update the UI with Deliverd tick
        case SENT:
        //Sent message update the UI with sent tick
        default:
            break
        }

Location message JSON parsing

You can parse the location message and show in stack map view

NSData *objectData = [message.message dataUsingEncoding:NSUTF8StringEncoding];
NSDictionary *jsonStringDic = [NSJSONSerialization JSONObjectWithData:objectData                                                                  options:NSJSONReadingMutableContainers
                                                                    error:&error];
  
NSArray* latLog = [[NSArray alloc] initWithObjects:[jsonStringDic valueForKey:@"lat"],[jsonStringDic valueForKey:@"lon"], nil];

NSString *latLongArgument = [NSString stringWithFormat:@"%@,%@", latLog[0], latLog[1]];
let objectData: Data? = message.message.data(using: String.Encoding.utf8.rawValue)
 var jsonStringDic: [AnyHashable : Any]? = nil
    if let aData = objectData {
            jsonStringDic = try? JSONSerialization.jsonObject(with: aData, options: .mutableContainers) as? [AnyHashable : Any]
     }
 let latLog = [jsonStringDic?["lat"], jsonStringDic?["lon"]]

 let latLongArgument = "\(latLog[0]),\(latLog[1])"

Delete Conversation thread

If you want to delete all the messages with a user you can check the below code:

📘

NOTE

If the message has been sent then calling this API won't delete the message from the receiver's device.

// If it's a channel then pass channel Id
// Or pass the userId with whom you want to delete all the conversations
[ALMessageService deleteMessageThread:userId
                             orChannelKey:nil
                           withCompletion:^(NSString *string, NSError *error) {

                               if(error == nil)
                               {
                                                                    // Success
                               }
 }];
// If it's a channel then pass channel Id
// Or pass the userId with whom you want to delete all the conversations
ALMessageService.deleteMessageThread(conversation.contactIds, orChannelKey: nil, withCompletion: {
      _,error in
      guard error == nil else { return }
      // Success
}

Marking the chat thread as a read or single message

You can update the read status of a complete conversation thread by calling the below method:

a) Mark the conversation read for the group by passing a channel key

[self.applozicClient markConversationReadForGroup:CHANNEL_KEY withCompletion:^(NSString *response, NSError *error) {

        if (!error){
            NSLog(@"Failed to mark conversation as read for group");
            return;
        }
}];
applozicClient.markConversationRead(forGroup:CHANNEL_KEY) { (response, error) in
            guard error == nil else {
                print("Failed to mark conversation as read for group chat")
                return
            }
}

b) Mark conversation read for one to one by passing a userId of receiver

[self.applozicClient markConversationReadForOnetoOne:@"RECIEVER_USERID" withCompletion:^(NSString *response, NSError *error) {

        if (!error){
            NSLog(@"Failed to mark conversation as read for one to one chat");
            return;
        }
}];
applozicClient.markConversationRead(forOnetoOne: RECIEVER_USERID) { (response, error) in
            guard error == nil else {
                print("Failed to mark conversation as read for one to one chat")
                return
            }
                                                                    
  }

❗️

Setup ApplozicClient

Note: You need to setup ApplozicClient before using the methods refer to this link

Updated 12 days ago



iOS


Chat View Controller

Suggested Edits are limited on API Reference Pages

You can only suggest edits to Markdown body content, but not to the API spec.