Menu

Expand
Rate this page:

Chat with iOS and Swift

Programmable Chat has been deprecated and is no longer supported. Instead, we'll be focusing on the next generation of chat: Twilio Conversations. Find out more about the EOL process here.

If you're starting a new project, please visit the Conversations Docs to begin. If you've already built on Programmable Chat, please visit our Migration Guide to learn about how to switch.

As the Programmable Chat API is set to sunset in 2022, we will no longer maintain these chat tutorials.

Please see our Conversations API QuickStart to start building robust virtual spaces for conversation.

Ready to implement a chat application using Twilio Chat Client? Here is how it works at a high level:

  1. Programmable Chat is the core product we'll be using to handle all the chat functionality.
  2. We use a server side app to generate user access tokens which contains all your Twilio account information. The Programmable Chat Client uses this token to connect with the API.

Properati built a web and mobile messaging app to help real estate buyers and sellers connect in real time. Learn more here.

For your convenience, we consolidated the source code for this tutorial in a single GitHub repository. Feel free to clone it and tweak as required.

Let's get started!

Initialize the Programmable Chat Client

The only thing you need to create a client is an access token. This token holds information about your Twilio account and Programmable Chat API keys. We have created a web version of Twilio chat in different languages. You can use any of these to generate the token:

You will need to setup your access token URL in the Keys.plist file in the resources folder. The default is http://localhost:8000/token - you may need to change this. For instance, if you set up the Node.js version of the chat server (listed above) - this URL would be http://localhost:3000/token

Loading Code Sample...
        
        
        twiliochat/MessagingManager.swift

        Fetch Access Token

        twiliochat/MessagingManager.swift

        Now it's time to synchronize your Twilio Client.

        What's this "synchronizing" about?

        Synchronize the Programmable Chat Client

        The synchronizationStatusChanged delegate method will allow us to know when the client has loaded all the required information. You can change the default initialization values for the client using a TwilioChatClientProperties instance as the options parameter in the previews step.

        We need the client to be synchronized before trying to get the channel list (next step). Otherwise, calling client.channelsList() will return nil.

        Loading Code Sample...
              
              
              twiliochat/MessagingManager.swift

              Synchronize the Chat Client

              twiliochat/MessagingManager.swift

              We've initialized the Programmable Chat Client, now lets get a list of channels.

              Get the Channel List

              Get the Channel Descriptor List

              Our ChannelManager class takes care of everything related to channels. In the previous step, we waited for the client to synchronize channel information, and assigned an instance of TCHChannels to our ChannelManager.

              Now we will get a list of light-weight channel descriptors to use for the list of channels in our application. We combine the channels the user has subscribed to (both public and private) with the list of publicly available channels. We do need to merge this list, and avoid adding duplicates. We also sort the channel list here alphabetically by the friendly name.

              Loading Code Sample...
                    
                    
                    twiliochat/ChannelManager.swift

                    Get Channel List

                    twiliochat/ChannelManager.swift

                    Let's see how we can listen to events from the chat client so we can update our app's state.

                    Listen to Client Events

                    Listen to Client Events

                    The Programmable Chat Client will trigger events such as channelAdded or channelDeleted on our application. Given the creation or deletion of a channel, we'll reload the channel list in the reveal controller. If a channel is deleted and we were currently joined to that channel, the application will automatically join the general channel.

                    ChannelManager is a TwilioChatClientDelegate. In this class we implement the delegate methods, but we also allow MenuViewController class to be a delegate of ChannelManager, so it can listen to client events too.

                    Loading Code Sample...
                          
                          
                          twiliochat/ChannelManager.swift

                          Listen for Client Events

                          twiliochat/ChannelManager.swift

                          Next, we need a default channel.

                          Join the General Channel

                          Join the General Channel

                          This application will try to join a channel called "General Channel" when it starts. If the channel doesn't exist, it'll create one with that name. The scope of this example application will show you how to work only with public channels, but the Programmable Chat client allows you to create private channels and handle invitations.

                          Once you have joined a channel, you can register a class as the TCHChannelDelegate so you can start listening to events such as messageAdded or memberJoined. We'll show you how to do this in the next step.

                          Loading Code Sample...
                                
                                
                                twiliochat/ChannelManager.swift

                                Join or Create a General Channel

                                twiliochat/ChannelManager.swift

                                Now let's listen for some channel events.

                                Listen to Channel Events

                                Listen to Channel Events

                                We registered MainChatViewController as the TCHChannelDelegate, and here we implemented the following methods that listen to channel events:

                                • messageAdded: When someone sends a message to the channel you are connected to.
                                • channelDeleted: When someone deletes a channel.
                                • memberJoined: When someone joins the channel.
                                • memberLeft: When someone leaves the channel.
                                • synchronizationStatusChanged: When channel synchronization status changes.

                                As you may have noticed, each one of these methods include useful objects as parameters. One example is the actual message that was added to the channel.

                                Loading Code Sample...
                                      
                                      
                                      twiliochat/MainChatViewController.swift

                                      Listen to Channel Events

                                      twiliochat/MainChatViewController.swift

                                      We've actually got a real chat app going here, but let's make it more interesting with multiple channels.

                                      Join Other Channels

                                      Join Other Channels

                                      The application uses SWRevealViewController to show a sidebar that contains a list of the channels created for that Twilio account.

                                      When you tap on the name of a channel from the sidebar, that channel is set on the MainChatViewController. The joinChannel method takes care of joining to the selected channel and loading the messages.

                                      Loading Code Sample...
                                            
                                            
                                            twiliochat/MainChatViewController.swift

                                            Join Other Channels

                                            twiliochat/MainChatViewController.swift

                                            If we can join other channels, we'll need some way for a super user to create new channels (and delete old ones).

                                            Create a Channel

                                            Create a Channel

                                            We use an input dialog so the user can type the name of the new channel. The only restriction here is that the user can't create a channel called "General Channel". Other than that, creating a channel is as simple as calling createChannel and passing a dictionary with the new channel information.

                                            Loading Code Sample...
                                                  
                                                  
                                                  twiliochat/ChannelManager.swift

                                                  Create a Channel

                                                  twiliochat/ChannelManager.swift

                                                  Cool, we now know how to create a channel, let's say that we created a lot of channels by mistake. In that case, it would be useful to be able to delete those unnecessary channels. That's our next step!

                                                  Delete a Channel

                                                  Delete a Channel

                                                  Deleting a channel is easier than creating one. We'll use the UITableView ability to delete a cell. Once you have figured out what channel is meant to be deleted (from the selected cell index path), deleting it is as simple as calling the channel's method destroy.

                                                  Loading Code Sample...
                                                        
                                                        
                                                        twiliochat/MenuViewController.swift

                                                        Delete a Channel

                                                        twiliochat/MenuViewController.swift

                                                        That's it! We've built an iOS application with Swift. Now you are more than prepared to set up your own chat application.

                                                        Where to next?

                                                        Where to Next?

                                                        If you are an iOS developer working with Twilio, you might want to check out this other project:

                                                        Notifications Quickstart

                                                        Twilio Notifications for iOS Quickstart using Swift

                                                        Did this help?

                                                        Thanks for checking out this tutorial! If you have any feedback to share with us, we'd love to hear it. Tweet @twilio to let us know what you think.

                                                        Mario Celi Jeff Linwood David Prothero Kat King Andrei Birjukov Viktoria Bashkite Andrew Baker Jose Oliveros Jeffrey Linwood Sarah Stringer Cristhian Motoche
                                                        Rate this page:

                                                        Need some help?

                                                        We all do sometimes; code is hard. Get help now from our support team, or lean on the wisdom of the crowd by visiting Twilio's Stack Overflow Collective or browsing the Twilio tag on Stack Overflow.

                                                        Loading Code Sample...
                                                              
                                                              
                                                              

                                                              Thank you for your feedback!

                                                              Please select the reason(s) for your feedback. The additional information you provide helps us improve our documentation:

                                                              Sending your feedback...
                                                              🎉 Thank you for your feedback!
                                                              Something went wrong. Please try again.

                                                              Thanks for your feedback!

                                                              thanks-feedback-gif