Business Productivity

Build chat applications in iOS and Android with Amazon Chime SDK messaging

Overview

Amazon Chime SDK messaging provides building blocks for developers to make it easier to connect communities of users with secure, scalable, and persistent messaging. In many cases, developers have use cases that require building chat into mobile applications. For example, they may be connecting delivery drivers to customers, doctors to patients, or two people starting to get to know each other on a dating application. To build these experiences, they require a SDK with messaging support for iOS and Android.

In this blog, we will walk through iOS and Android chat demo applications built with the AWS SDK for iOS and the AWS SDK for Android, both of which now include messaging APIs from the Amazon Chime SDK. This approach helps customers build real-time chat functionality into their iOS and Android applications without having to worry about managing and scaling a complex infrastructure.

After completing this blog, you will have a simple mobile chat application that displays messages from all channels a user is a member of in a single view. From here you can add automated moderation, sentiment analysis, profanity filtering, video calls, conversational interfaces with bots, and more.

Prerequisites

Note: Deploying the chat demo application and receiving traffic from the demo created in this post will incur AWS charges.

Demo Application Architecture

The diagram below explains the architecture of the mobile chat demo applications built with Amazon Chime SDK messaging. The deployment of the AWS CloudFormation stack in the prerequisites section creates an Amazon Chime AppInstance, which acts as the data plane for all messages. It also creates an authentication layer using Amazon Cognito, and an Amazon Simple Storage Service (Amazon S3) bucket to store attachments.

Amazon Chime SDK messaging for iOS and Android contains two sets of APIs to operate on each platform.

  1. AWS SDK – This includes aws-sdk-ios AWSChimeSDKMessaging and aws-sdk-android aws-android-sdk-chimesdkmessaging. They are used to manage Amazon Chime SDK messaging resources, i.e. members and channels, messages, etc.
  2. Receiving APIs – These are written in Kotlin for Android and Swift for iOS, and are part of the client application. They are used to establish and manage a WebSocket connection and receive messages. For this demo we have selected two open-source WebSocket libraries, Starscream for iOS, and okhttp for Android. Additional details for each library are provided below.
    • Starscream is used in iOS, which is under Apache License, Version 2.0.
      • A WebSocket library with many active users.
      • A Github project with active issues and pull requests.
      • Work with iOS 8+
      • Alternative – URLSessionWebSocketTask
      • Add dependency in Pod file pod 'Starscream', '~> 4.0.0'
    • okhttp is used in Android, which is under Apache License, Version 2.0.
      • A Http client with WebSocket support since v3.5
      • Documentation is available
      • Work with Android 5.0+ (API level 21+)
      • Alternative – https://github.com/Tinder/Scarlet
      • Add dependency in build.gradleimplementation 'com.squareup.okhttp3:okhttp:4.9.0'

Key features of the mobile chat demo applications include:

  1. User authentication by Amazon Cognito OR Credential Exchange Service.
  2. Ability to initiate messaging client using aws-sdk-ios or aws-sdk-android.
  3. Ability to fetch the messaging session endpoint, construct a sigv4 signed URL, then establish a WebSocket connection between the device and the Amazon Chime SDK messaging service to receive and process messages.
  4. Ability to manage channels, manage channel members, and send messages.

Setting up the Amazon Chime SDK iOS and Android Chat Demo Applications

By completing the steps below, you will learn how to run the Amazon Chime SDK iOS and Android chat demo applications on your mobile device or on a simulator. These applications enable users to send and receive messages in chat channels in real time. Both applications are designed in a way that can be used as a starting point for your own application, or as a quick way to explore the features of the Amazon Chime SDK messaging.

Build and Run Chat Demo Applications

Clone the project from Github.

git clone https://github.com/aws-samples/amazon-chime-sdk.git

iOS

  1. Run the following command to navigate to the root folder of the iOS chat demo application.
    cd apps/chat-ios
  2. Run the following command to install dependencies.
    pod install
  3. Open AmazonChimeMessagingSDKDemo.xcworkspace using Xcode.
  4. Open AmazonChimeMessagingSDKDemo/amplifyconfiguration.json. Add the following configuration to it, and replace the values in <>.
    {
        "auth": {
            "plugins": {
                "awsCognitoAuthPlugin": {
                    "IdentityManager": {
                        "Default": {}
                    },
                    "CredentialsProvider": {
                        "CognitoIdentity": {
                            "Default": {
                                "PoolId": "<cognitoIdentityPoolId from CloudFormation Outputs>",
                                "Region": "us-east-1"
                            }
                        }
                    },
                    "CognitoUserPool": {
                        "Default": {
                            "PoolId": "<cognitoUserPoolId from CloudFormation Outputs>",
                            "AppClientId": "<cognitoAppClientId from CloudFormation Outputs>",
                            "Region": "us-east-1"
                        }
                    },
                    "Auth": {
                        "Default": {
                            "authenticationFlowType": "USER_SRP_AUTH"
                        }
                    }
                }
            }
        },
        "storage": {
            "plugins": {
                "awsS3StoragePlugin": {
                      "bucket": "<attachments_s3_bucket_name from CloudFormation Outputs>",
                      "region": "us-east-1"
                }
            }
        }
    }
  5. Open AmazonChimeMessagingSDKDemo/AppConfiguration.swift. Add the following configuration to it.
    struct AppConfiguration {
        static let apiGatewayInvokeUrl = "<apiGatewayInvokeUrl from CloudFormation Outputs>"
        static let appInstanceArn = "<appInstanceArn from CloudFormation Outputs>"
        static let region = "us-east-1"
    }
  6. Run the application on a simulator or a physical device. Sign in with username and password of desired Amazon Cognito user or through Credential Exchange Service.

Android

  1. Run the following command to navigate to the root folder of the Android chat demo application.
    cd apps/chat-android
  2. Open the project in Android Studio. Open app/src/main/res/raw/amplifyconfiguration.json. Add the following configuration to it, and replace the values in <>.
    {
        "UserAgent": "aws-amplify-cli/2.0",
        "Version": "1.0",
        "auth": {
            "plugins": {
                "awsCognitoAuthPlugin": {
                    "IdentityManager": {
                        "Default": {}
                    },
                    "CredentialsProvider": {
                        "CognitoIdentity": {
                            "Default": {
                                "PoolId": "<cognitoIdentityPoolId from CloudFormation Outputs>",
                                "Region": "us-east-1"
                            }
                        }
                    },
                    "CognitoUserPool": {
                        "Default": {
                            "PoolId": "<cognitoUserPoolId from CloudFormation Outputs>",
                            "AppClientId": "<cognitoAppClientId from CloudFormation Outputs>",
                            "Region": "us-east-1"
                        }
                    },
                    "Auth": {
                        "Default": {
                            "authenticationFlowType": "USER_SRP_AUTH"
                        }
                    }
                }
            }
        }
    }
  3. Open app/src/main/java/com/amazonaws/services/chime/sdkdemo/common/AppConstants.kt. Add the APP_INSTANCE_ARN and API_GATEWAY_INVOKE_URL to it.
    const val APP_INSTANCE_ARN = "<appInstanceArn from CloudFormation Outputs>"
    const val API_GATEWAY_INVOKE_URL = "<apiGatewayInvokeUrl from CloudFormation Outputs>"
  4. Run the application on a simulator or a physical Android device. Sign in with username and password of desired Amazon Cognito user or through Credential Exchange Service.

Test

After building and running your iOS and Android applications, you can test them by sending and receiving messages between the web demo application and mobile clients. In this demo, two users Carlos and Wei are created via Amazon Cognito User Pools and added into a channel named Private Channel. Carlos is signed into the web application, Wei is signed into the mobile application.

Note: The iOS demo application includes the feature of sending and receiving image attachments.

Optimizations

Battery consumption

Keeping the WebSocket connection open using a ping-pong mechanism will consume battery. The ping loop will have impact on CPU usage and power consumption, but it will consume more power when WiFi is constantly on. It is recommended to close the connection when the app goes to background and rely on push notification to notify for a new message.

WebSocket Reconnection

Since Amazon Chime SDK messaging maintains a ping-pong mechanism, the application can attempt to reconnect if the ping failed. The client could miss messages during network disruption or between reconnections. In this case, the client can call listChannelMembershipForAppInstanceUser, which returns all memberships and the lastMessageTimestamp for each channel. It can then only fetch messages for channel where there are missing messages. It will also know if it missed any membership events from the result of listChannelMembershipForAppInstanceUser.

Cleanup

If you don’t want to continue to be charged for the use of the chat demo application, you can clean up by deleting the stack and resources created in prerequisites.

To delete the stack and its resources:

  1. From the AWS CloudFormation console in the Region you used in the prerequisites, select the stack that you created.
  2. Click Delete Stack.
  3. In the confirmation message that appears, click Yes, Delete. At this stage, the status changes to DELETE_IN_PROGRESS. In the same way you monitored the creation of the stack, monitor its deletion by using the Events tab. When AWS CloudFormation completes the deletion of the stack, it removes the stack from the list.

Finally, delete the Amazon Chime app instance created using the following commands in CLI:
aws chime delete-app-instance --app-instance-arn <ARN FROM PREREQUISITES>

Conclusion

With the Amazon Chime SDK messaging features, customers are more easily able to build and customize their own messaging capabilities for their mobile applications. They don’t have to worry about the heavy lifting of managing a complex backend infrastructure. In this blog post, you learned about the Amazon Chime SDK messaging for iOS and Android, how to quickly spin up a chat application on both platforms.

To learn more about what you can build with Amazon Chime SDK messaging, please read our other messaging blog post: