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.
On a high-level, you’ll want to follow the next steps:
- Download the Real-time iOS Chat App Template (available here)
- Link your Firebase account to the app template
- Run the app in the latest version of Xcode.
- 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!
- 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.
- 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
- 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.
- 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.
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.
- 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.
- 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 - 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.
- 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. - 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.
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
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:
- Add a new view controller to your storyboard, that inherits the MyChatViewController class
- Add a segue (named “myChatSegue“) from your screen that triggers the chat to the newly added MyChatViewController
- 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.
(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:
- First, create a collection (“Add collection”), named “friendships“
- Now, find the user IDs of two users who are friends. Their IDs can be found in Firebase Authentication -> User UID column
- 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.
You should end up with two entries in the “friendships” table, similar to the following picture:
- 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.