In this tutorial, we’ll be focusing on how to get our Chat iPhone App Template up and running. The Swift template is working end-to-end, being integrated with Firebase Backend, where all the user & message data is being stored. In order to have your own instance of the real-time chat app, you’ll need to wire up the purchased app template to your own free Firebase account.

real-time ios chat app

On a high-level, you’ll want to follow the next steps:

  1. Download the Real-time iOS Chat App Template (available here)
  2. Link your Firebase account to the app template
  3. Run the app in the latest version of Xcode.
  4. Publish your app to Xcode

This document will also describe how to make your own real-time iOS Chat app in Swift, by leveraging our pre-made app template. Assuming you’ve already downloaded the Chat template, let’s get started!

Create and configure a new Firebase iOS Project

First of all, you need to configure your backend. This is the server where all the users, groups, & messages are being stored. Firebase is a service provided by Google, which helps app makers with their server-side implementation. It has amazing features, such as database, authentication, storage, notifications, analytics, etc. And best of all, it’s completely free!

  1. Go to Firebase, log into your Google account and create a new project. If you already have a Firebase project for your chat app, you can skip this step.
    firebase create project iOS Chat app template
  2. In Firebase, add a new iOS App to your newly created project
    Now that you have a Firebase project, you can add a new iOS app, which will represent the backend of your chat app. Tap the “+” button showing up below the project’s title on the main Firebase dashboard, choose “iOS”, fill in the bundle identifier with “io.instamobile.ChatApp” and create your app
    create iOS Firebase app backend chat real time
  3. Enable Firebase Authentication
    Since our app template comes with both Email & Password login and Facebook Login, you’ll need to enable these in Firebase, in order to accept user logins and registrations. To do that, locate the Authentication tab in the left side menu -> Sign-in Methods -> Enable Email/Password and Facebook.
    firebase authentication iOS swift backend chat create account
  4. Enable Read/Write permissions to Firestore
    In Firebase Console, head over to Database -> Cloud Firestore -> Rules, and override the permissions to the database to:

    service cloud.firestore {
      match /databases/{database}/documents {
        match /{document=**} {
          allow read, write;
        }
      }
    }

    This will allow your iOS app to write data to Firestore. Unless you enable these permissions, your app won’t work properly, since by default, write permissions for Cloud Firestore are off.
    write firestore swift

Link the downloaded iOS app template to your Firebase Project

Now that you have your own Firebase project, it’s time to modify the app template to use your Firebase server, rather than our mock project. Doing this is pretty simple:
1. Go to Firebase Console -> Project Overview -> Settings -> Select your iOS app -> Download “GoogleService-Info.plist” file
2. Locate the existing GoogleService-Info.plist file in the downloaded Swift source-code (it’s in ChatApp/ChatApp/GoogleService-Info.plist) and replace it with the one you’ve just got from Firebase.

Build & Run the app with Xcode

Now that you’ve configured your Firebase backend, and you hooked it up to the app template, it’s time to see the real-time chat app in action.

  1. Install the app dependencies (called “pods”)
    To do this, open up a terminal window, locate the Podfile file, (it’s in that ChatApp folder) and install the pods by running:

    cd ~/path_to_downloaded_folder/ChatApp
    pod install

    If you don’t have Cocoapods installed, check out their website to get started.

  2. Open ChatApp.xcworkspace in Xcode
    Running “pod install” should generate a .xcworkspace file in the same folder with Podfile. Double click on it, or run “open ChatApp.xcworkspace” in your terminal. This will open your entire Swift project in Xcode
  3. Build & Run the chat app in Xcode
    Choose which simulator you want to run (or plug in your iPhone device) and click “Run“. This will install the Chat app on the chosen device.
    xcode app templates build run chat
  4. Play around with the app, by creating an account (email/password or Facebook Login).
    You’ll notice the newly created account in Firebase -> Authentication. You’re also supposed to see the “users” table now (in Database -> Firestore), containing the newly created user info. The home screen will be empty though, and you won’t be able to search for any friends) – this is expected since there are no friendships so far.
  5. Create more accounts
    You’ll need more users, in order to have a proper Chat app, so go ahead and create more accounts, via the iOS app. You can also create them manually, in Firebase -> Authentication -> Add User.

Add the friendships between users

In order to be able to create chat rooms, you need to create a few friendships between your users (the accounts you registered at the previous step). Add a few friends in the Search screen, and then accept those friend requests, from the corresponding users’ accounts. Once you have people in the Contacts tab, you can start chatting with them. You can also start creating groups, once there are at least two friends to group-chat with.

swift chat app

The backend database of our real-time chat app primarily consists of 4 tables:
– “users” – storing all the user data, such as id, email, name & profile photo
– “friendships” – storing all the friendship relations between users
– “channels” – storing all the messages being sent in all the groups and 1-1 conversations
– “channel_participation” – mapping users to channels (“User X is participating in the conversation channel Y”).

How to Enable Push Notifications

In order to enable push notifications, we need to integrate Apple, Firebase and our app. The process of enabling push notifications with Apple requires you to generate a certificate on Apple Developer’s website, upload that into Firebase and then update the authorization key in the app template. Follow our tutorial on Firebase Push Notifications, for a step by step guide on how to enable push notifications with Apple and Firebase in Swift.

To update the Authorization Key in the app template, simply open ATCPushNotificationSender.swift file, locate line 24, and update the key with your own:

request.setValue("key=AAAA6JevPJU:APA91bEfLj2bt_AXyHzYQLr2psBYW8QfF5KWNtVPhfkEZHRZyBtpU2xFhDAU535ENRLFGCTRmqLaPcZRoUOPByzGpAB8pSIM8Kalvwo6WAsl3jImO1WgUHEEdP6lasL88v-p0i4MCpgY", forHTTPHeaderField: "Authorization")

You can find your Authorization Key in Firebase Console -> Project Settings -> Cloud Messaging -> Server Key
swift cloud messaging

We hope this tutorial has been helpful in teaching you how to make a real-time chat iOS app in Swift by leveraging our premium app template. Please let us know if you encounter any issues or if there’s anything missing.

How do I integrate a Chat into my existing iOS app?

Opening a chat room programmatically

All you need to do to instantiate a view controller that displays a chat room is this:

func openChatRoom() {
    let user = ATCUser(firstName: "Test F", lastName: "Test L")
    let channel = ATCChatChannel(id: "idc", name: "Group Test")
    let uiConfig = ATCChatUIConfiguration(primaryColor: UIColor(hexString: "#0084ff"),
                                          secondaryColor: UIColor(hexString: "#f0f0f0"),
                                          inputTextViewBgColor: UIColor(hexString: "#f4f4f6"),
                                          inputTextViewTextColor: .black,
                                          inputPlaceholderTextColor: UIColor(hexString: "#979797"))
    let vc = ATCChatThreadViewController(user: user, channel: channel, uiConfig: uiConfig)
    navigationController?.pushViewController(vc, animated: true)
    // or
    // self.present(vc, animated: true, completion: nil)
}

As you can see, you need to specify the user who opens the chat room, the channel that is being opened (can be a 1-1 conversation, a group chat, etc – all it matters is its ID), as well as the UI colors you prefer for your chat.

Opening the chat home screen in Storyboards

To open the home screen of our chat app in your existing app, via Storyboards, you’ll need to follow the next steps:

  1. Add a new view controller to your storyboard, that inherits the MyChatViewController class
  2. Add a segue (named “myChatSegue“) from your screen that triggers the chat to the newly added MyChatViewController
  3. In the view controller that triggers the segue, add the following code
    override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
       if (segue.identifier == "myChatSegue") {
           if let destinationVC = segue.destination as? MyChatViewController {
               destinationVC.user = ATCUser(firstName: "Florian", lastName: "Marcu") // use whatever user you prefer
           }
       }
    }

Database Schema

In this section, we are presenting the Firebase database schema for our real-time iOS Chat app, to give you an idea of how a correct setup looks like as well as what it’d take for you to adapt this database to your app’s needs.

real-time iOS appchat firebase ioschat firebasechat firestore swiftchat firebase swift

(Legacy) How do I add friendships manually?

In the initial version of our chat app template, customers had to add friendships manually. This can still be useful if you are importing data from an existing database, automatically. Or, simply if you want to move faster by avoiding to switch between lots of accounts.

To create a friend relationship manually, go to Database -> Cloud Firestore and create a “friendships” table that looks like this:
group chat friends iOS app backend

  1. First, create a collection (“Add collection”), named “friendships
  2. Now, find the user IDs of two users who are friends. Their IDs can be found in Firebase Authentication -> User UID column
    firebase authentication user id
  3. Add two new documents to the “friendships” collection.
    In order to make two users friends, you need to add two new entries to the friendships table, matching their user IDs. Go to Database -> Firestore -> “friendships” and click “Add Document“. Use an auto-ID and add two fields: user1 and user2, and enter the two user IDs located at the previous step as the values. Then click “Save“. Do this again, by making sure you switch the order of these two users (user1 becomes user2 and vice-versa). This is to ensure both users are friends with each other since the friend relationship is not bidirectional.
    firebase friendship friends users table firestore firebase friendship friends users table firestore
    You should end up with two entries in the “friendships” table, similar to the following picture:
    friendships table firestore
  4. Run the iPhone Chat app (in Xcode or Device) again
    Make sure you log in with a user for whom you’ve already added friendships in the database. Now, the app will list all the friends on the home screen, and you’ll be able to search for users on the search screen. You’ll also be able to create chat channels, chat groups and send messages & photos between friends.

Shopping Cart