Introduction

This tutorial will provide you with complete guidance on how to add chat features to your iOS application. To get started, we will download the MirrorFly Chat SDKs and configure them on your Xcode project.

Below are the requirements we’ll need to develop this app.

Technology Behind Building iOS Chat App with Swift

Before getting into the technical stuff this tutorial assumes a basic understanding of Swift. Thus, it is integral for you to have some idea about the requirements, the working process, technical terminologies, and more.

Basic Requirements for iOS Chat App

This Swift tutorial was built with the below requirements,

  • Xcode 13 or later
  • iOS 12.1 or later
  • Swift 5.0 or later

Initial Setup for iOS Chat App

To start with, it is essential to have some initial setup to be done with MirrorFly in your application. This includes the below steps,

  • Get your Applications SDK license key
    • a) Create your MirrorFly Console Account
  • Installation Process
  • Integrate Chat SDK
  • Configure the SDK server & Data
  • Initialize Chat SDK
  • Registration
  • Connect to the Chat Server
  • Disconnect Chat Server
  • Observe Connection Events
  • Sending and Receiving of messages

Now, this initialization process starts with installation, which is followed by preliminary steps of Chat SDKs implementation.

Let’s have a look in detail on the above specified notes for better understanding,

1 . SDK License Key

To use any SDK while planning to build an iOS chat app using swift technology, you must be assured about authentication checks as to whether your SDKs are authenticated by the MirrorFly server or not.

Moreover, to go with this authentication check it’s must to make use of the master License Key which is there in your dashboard. But be aware that the master API token can never be changed or revoked.

This SDK license key is a must for your MirrorFly application before proceeding with MirrorFly Chat SDK. Now, to obtain your license key you need to create a free MirrorFly account.

I. Create your MirrorFly Console Account

To create a MirrorFly account you have follow the below steps,

Step 1 : To create an account you need to Sign up into the MirrorFly Console page using https://console.mirrorfly.com/register.

Step 2 : Here, you can provide your basic details such as your name, organization details, contact number, and work email, to get enrolled .

Step 3 : You get into the account! This lets you navigate across the content on your MirrorFly account.

Step 4 : Now, to get access to the license key - click on the ‘Overview page’ and downloadable iOS SDK file to move ahead with the integration process.

#

Step 5 : Simply copy the license key under "Application info" in the "Overview" page and go ahead with further installation process.

#

But, here you have to extract the chat SDK files which will have a check in detail in the next installation section.

2 . Installation Process for iOS Chat App

To begin with the installation process, the file has to be imported into the project with the support of swift technology. This is carried out using some of the below steps,

Step 1 : To download the latest SDK from MirrorFly, you need to first click on the framework.

Step 2 : downloading the files - the extracted files are as follows,


                                             FlyCore.xcframework
                                             FlyCommon.xcframework
                                             FlyNetwork.xcframework
                                             FlyDatabase.xcframework
                                             FlyXmpp.xcframework
                                             FlyTranslate.xcframework
                                        
#

3 . Integrate Chat SDK for iOS Chat App

Step 1 : Create a new iOS project or open an existing project if any.

Step 2 : Add the extracted frameworks in your project's app folder to start proceeding with the integration process to build your chat app for iOS

     
                              Goto Project ->  Target -> General -> Frameworks,libraries and Embedded Content -> Select Embed & Sign for all the Chat SDK's xcframeworks
                            
#

Step 3 : Now, disable all the bitcodes from your project.

     
                              Goto Project -> Build Settings -> Filter the term `Bitcode` -> and select No from the dropdown
                            
#

Step 4 : now if you have not initiated any pods project, then it's time to initiate one. Once you have completed with initiation, add the required pods that are necessary for the SDK so that the execution can take place properly.

  
                              pod 'libPhoneNumber-iOS'
                              pod 'Alamofire'
                              pod 'RealmSwift', '10.20.1'
                              pod 'XMPPFramework/Swift'
                              spod 'SocketRocket'
                              pod 'Socket.IO-Client-Swift'
                            

Step 5 : Now, add the below given pod hook code block at the end of the pod file and finalize the installation of the pods.

  
                                    post_install do |installer|
                                    installer.pods_project.targets.each do |target|
                                    target.build_configurations.each do |config|
                                    config.build_settings['IPHONEOS_DEPLOYMENT_TARGET'] = '12.1'
                                    config.build_settings['ENABLE_BITCODE'] = 'NO'
                                    config.build_settings['APPLICATION_EXTENSION_API_ONLY'] = 'No'
                                    config.build_settings['BUILD_LIBRARY_FOR_DISTRIBUTION'] = 'YES'
                                end
                                end
                                end
                            
#

Step 6 : all the mentioned capabilities into your project.

Capabilities

  • App Groups
  • Background Modes

Now, go back to the background mode and enable all the below provided modes.

Background Modes

  • Audio, Airplay, and Picture in Picture
  • Background fetch
  • Remote notifications
#

4. Configure the SDK Server & Data for iOS Chat App

To access the data across the world there is a need to configure the server detail which can be done using AppDelegate class methods as follows,

  
                                let BASE_URL = "https://api-preprod-sandbox.mirrorfly.com/api/v1/"
                                let LICENSE_KEY = "xxxxxxxxxxxxxxxxxxxxxx"
                                let CONTAINER_ID = "xxxxxxxxxxxxxxxxxxxxxx"
                           

Now, the above are the regular steps that take place in all the chat app development. But let’s be specific about Swift technology in further.

5. Initialize Chat SDK for iOS Chat App

To begin with initialization, you require certain basic data to get started with MirrorFly Chat SDK. In this tutorial, we make use of the ChatSDK class and AppDelegate class from 'didFinishlaunchingWithOptions' and other related data to build a ChatSDK builder. Further, we will follow the below mentioned method to proceed with the development process.

  
                            try? ChatSDK.Builder.setAppGroupContainerID(containerID: CONTAINER_ID)
                            .setLicenseKey(key: LICENSE_KEY)
                            .isTrialLicense(isTrial: true)
                            .setDomainBaseUrl(baseUrl: BASE_URL)
                            .buildAndInitialize() 
                                
#

6. New User Registration

Whether it’s one-to-one or group chat, to make or receive a text message you need to move across the authentication process via registration.

To proceed with registration, the user has to call the below method. This method is associated with both Sandbox mode registration as well as Live mode registration that is completely based on isTrialLicense provided in the ChatSDK.Builder class.

During the registration process, you must see to it that the method has been called only once until you have logged out of the session. Once the registration is called upon successfully, you can pass across the below auth tokens to chat SDK wherein it has been accepted as an optimal parameter.

  • APNS_DEVICE_TOKEN
  • VOIP_TOKEN
  • IS_EXPORT
 
                       try! ChatManager.registerApiService(for:  USER_IDENTIFIER ) { isSuccess, flyError, flyData in
                              var data = flyData
                               if isSuccess {
                                  // This is your Password
                                  guard let password = data["password"] as? String else{
                                      return
                               }
                               // This is your Username
                               guard let username = data["username"] as? String else{
                                   return
                               }
                              }else{
                                     let error = data.getMessage()
                                     print("#chatSDK \(error)")
                              }
                            }

                
                            
Argument Type Description
USER_IDENTIFIER String Unique Id to Register the User
APNS_DEVICE_TOKEN String Token to register APNS device (optional)
VOIP_DEVICE_TOKEN String Token to register VoIP device (optional)
IS_EXPORT Bool true for production (apns certificate) builds and false for sandbox (apns certificate) builds
CALLBACK FlyCompletionHanlder FlyCompletionHanlder is implemented and expressed as lambda expression for easy reading

7. Key Points to be Noted Before Text Messaging

Whenever you want to send a text message you have to establish a connection with the chat server. Let’s see this in detail with a variety of server processes like connect, disconnect, and more.

I. Connect to the Chat Server

You can use the below method to make a connection with the chat server.

 
                               ChatManager.connect() 
                            

II. Disconnect the Chat Server

If you want to disconnect the chat conversation, you can simply use the below method to close the chat from your end.

 
                                ChatManager.disconnect() 
                            

III. Observe Connection Events

Furthermore, if you wish to have a track of your present connection status for further conversation, you can do that by confirming the ‘ConnectionEventDelegate.’

But, you must set a 'delegate' in your ViewController's viewDidAppear method as given below,

 
                               ChatManager.shared.connectionDelegate = self 
                            

Once, you have set this in 'ConnectionEventDelegate,' you will be able to receive the connection status updates instantly via delegate method as below.

 
                                    func onConnected() {
                                        // Navigate to Conversation screen 
                                    }                          
                            

IV. Common Terminologies Used in Chat SDK Builder

Well, there are certain terminologies that are often used throughout the iOS chat app development process. So, let's have some understanding about them with their description in detail.

Keyword Description
userID/userBareID Unique ID assigned for each user Ex: 12345678 (any alphanumeric). The below characters is not allowed in userId: U+0022 (") U+0026 (&) U+0027 (') U+002F (/) U+003A (:) U+003C (<) U+003E (>) U+0040 (@) userID should follow below specification: https://xmpp.org/extensions/xep-0106.html
userJid (or) JID userID+@+domain of the chat server Ex.12345678@xmpp.chatsystem.dev.contus.us
groupID/groupBareID Unique ID assigned for each group Ex: group123456 (any alphanumeric). GroupJID = groupID +@mix.+domain of the chat server Ex:group123456@mix.xmpp.mirrorfly.dev.contus.us

From the above steps, once you have obtained all the understanding with the chat server connections and the fundamental terminologies used in the connection. Now, It’s time to go ahead with the text messaging process using swift on your iOS device.

8. One-to-one Text Message

I. Send a Text Message

Finally, now you can send a text message from one user to another using the below method.

But, here you need to create a unique user id for which you must call the other user's using username method String userJID = FlyUtils.getJid(USERNAME)

 
                                        FlyMessenger.sendTextMessage(TO_JID, TEXT) { isSuccess,error,chatMessage in
                                         if isSuccess {
                                              // Update the UI     
                                          }else{    
                                              // Handle the error    
                                         }    
                                        }    
                                                            
                                        
Argument Type Description
TO_JID String jid of the end user
TEXT String Specifies the text message that needs to be sent
REPLY_MESSAGE_ID String Provides the Message ID of replied message or else generates an empty string (optional)
CALLBACK SendMessageListener callback to observe the action status

II. Receive a Text Message

To receive a one-to-one text message you need to set the delegate in your ViewController's viewDidAppear method using below codes.

 
                                                ChatManager.shared.messageEventsDelegate = self                         
                                        

Now, confirm the MessageEventsDelegate class as this will allow you to see other incoming messages and related events.

  
                                func onMessageReceived(message: ChatMessage, chatJid: String) {
                                       // Message received from chatJid, content is message.messageTextContent
                                    }
                            

These are the common ones, but if you want using our Chat SDK support you can explore more functionalities.

Conclusion

To sum up, this tutorial walked you through the steps to create a chat app on Xcode, integrate MirrorFly SDKs using Swift, and deploy your chat app on the MirrorFly server. You can also access the full code of this tutorial on our Github repository.

We hope you now have a clear understanding of the next steps with your app development. Considering the same, we encourage you to explore our other in app interaction features on our Tutorial.

Launch your Own iOS Chat App with Swift!

Get Started with MirrorFly SDK's and Improve your overall in-app conversion, engagement, and retention.

  • Average API response 3s
  • 100ms worldwide latency
  • 1 Billion+ Conversations
Contact Sales
#
Integrate Our SDKs In Just 20 Mins!

Integrate Our Video, Voice & Chat SDKs into any app in < 30 mins

Contact Sales
#
Get Started With Our Self-hosted Chat Solution Today!

Get Full Access To Our Customizable Video, Voice & Chat SDKs!

Request Demo
Request Demo
Need to build a complete chat app? Let our experts help you out.
Hire Our Team