Quick Start

Learn how to add CometChat to your iOS app in minutes.

This guide demonstrates how to add chat to an iOS application using CometChat. Before you begin, we strongly recommend you read the Key Concepts guide.

👍

Improvements in V3.0

Faster connection & response times
Higher rate limits
Supports up to 100K users in a group
Unlimited groups
Support for Transient Messages
Real-time user & group members count
And more!

I want to explore iOS sample apps.

Import the app into Xcode and follow the steps mentioned in the README.md file.

Download Swift Chat App

Download Obj-c Chat App


Get your Application Keys

Signup for CometChat and then:

  1. Create a new app
  2. Head over to the API & Auth Keys section and note the Auth Key, App ID & Region

👍

Minimum Requirement

  1. Xcode 12 or above
  2. iOS 11 or higher

Add the CometChat Dependency

CocoaPods

We recommend using CocoaPods, as they are the most advanced way of managing iOS project dependencies. Open a terminal window, move to your project directory, and then create a Podfile by running the following command.

🚧

Note:

  1. CometChatPro SDK supports installation through Cocoapods only. Currently, we are supporting Xcode 12 or above versions of Xcode.

  2. CometChatPro SDK includes video calling components. We suggest you run on physical devices to avoid errors.

$ pod init

Add the following lines to the Podfile.

platform :ios, '11.0'
use_frameworks!

target 'YourApp' do
  pod 'CometChatPro', '3.0.3'
end

📘

Important

v3.0.2+ onwards, Voice & Video Calling functionality has been moved to a separate framework. In case you do not plan to use the calling feature, please add the Calling framework pod 'CometChatCalls', '2.1.1' in your app Podfile.

And then install the CometChatPro framework through CocoaPods.

$ pod install

If you're facing any issues while installing pods then use the below command.

pod install --repo-update

Always get the latest version of CometChatPro by command.

$ pod update CometChatPro

Setup Bitcode

You can set the Enable Bitcode setting to YES present in build settings in your XCode project.

❗️

If you are using CometChat Pro SDK having the version less than 2.0.8, then you need to set Enable Bitcode to NO

Swift Standard Libraries

CometChatPro framework build on Swift, you have to ensure the required libraries are embedded. This can be done by setting the “Always Embed Swift Standard Libraries” checkbox in your target’s build settings to “Yes”:

Set Header Search Path

Set the Header Search Paths to $SDKROOT/usr/include/libxml2.

Excluded Architecture

❗️

Warning!

For Xcode 12 and above, we need to add arm64 in the excluded architecture of build settings as Apple supports only arm architecture for simulators and actual devices. No support provided for X86_64 and i386 architectures.

Setting for build for active architecture

👍

Message

In Build Settings, enable active architecture to Yes

Setting up Excluded Architecture & Build active architecture onlySetting up Excluded Architecture & Build active architecture only

Setting up Excluded Architecture & Build active architecture only

Initialize CometChat

The init() method initializes the settings required for CometChat. We suggest you call the method on app startup preferably in the didFinishLaunchingWithOptions: method of the AppDelegate class.

import CometChatPro

class AppDelegate: UIResponder, UIApplicationDelegate{
{
   var window: UIWindow?
   let appId: String = "ENTER APP ID"
   let region: String = "ENTER REGION CODE"
    
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {

let mySettings = AppSettings.AppSettingsBuilder().subscribePresenceForAllUsers().setRegion(region: region).build()
        
  CometChat.init(appId: appId ,appSettings: mySettings,onSuccess: { (isSuccess) in
            if (isSuccess) {
                print("CometChat Pro SDK intialise successfully.")
            }
        }) { (error) in
                print("CometChat Pro SDK failed intialise with error: \(error.errorDescription)")
        }
        return true
    }
}
#import <CometChatPro/CometChatPro-Swift.h>

@interface AppDelegate ()

@end

@implementation AppDelegate


- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
  
  NSString *region = @"REGION";
  NSString *appID = @"YOUR_APP_ID";
    
    AppSettingsBuilder *appSettingBuilder = [[AppSettingsBuilder alloc]init];
    AppSettings *appSettings = [[[appSettingBuilder subscribePresenceForAllUsers]setRegionWithRegion:region]build];
    
    [[CometChat alloc]initWithAppId: appID appSettings:appSettings onSuccess:^(BOOL isSuccess) {
        NSLog(isSuccess ? @"CometChat Initialize Success:-YES" : @"CometChat Initialize Success:-NO");
    } onError:^(CometChatException * error) {
        NSLog(@"Error %@",[error errorDescription]);
    }];
    return YES;
}

Make sure you replace the appId with your CometChat App ID in the above code.

Register and Login your User

Once initialization is successful, you will need to create a user.
To create users on the fly, you can use the createUser() method. This method takes a User object and the API Key as input parameters and returns the created User object if the request is successful.

let newUser : User = User(uid: "user1", name: "Kevin") // Replace with your uid and the name for the user to be created.
let authKey = "AUTH_KEY" // Replace with your Auth Key.
CometChat.createUser(user: newUser, apiKey: authKey, onSuccess: { (User) in
      print("User created successfully. \(User.stringValue())")
  }) { (error) in
     print("The error is \(String(describing: error?.description))")
}

Once initialization is successful, you will need to log the user into CometChat using the login() method.

The login method needs to be called in the following scenarios:

  1. When the user is logging to the App for the first time.
  2. If the CometChat.getLoggedInUser() function returns nil.

❗️

Important

Kindly, make sure you add the check of CometChat.getLoggedInUser() function in your app where you check the App's user login status. In case it returns nil then you need to call the Login method inside it.

let uid    = "SUPERHERO1"
let authKey = "YOUR_AUTH_KEY"

if CometChat.getLoggedInUser() == nil {

    CometChat.login(UID: uid, apiKey: authKey, onSuccess: { (user) in

    print("Login successful : " + user.stringValue())

    }) { (error) in

    print("Login failed with error: " + error.errorDescription);

    }

}
NSString *uid    = @"SUPERHERO1";
NSString *apiKey = @"YOUR_API_KEY";

if ([CometChat getLoggedInUser == nil]){
  
[CometChat loginWithUID:uid apiKey:apiKey onSuccess:^(User * user) {
    
    // Login Successful
    NSLog(@" Login Successful :%@",[user stringValue]);
    
} onError:^(CometChatException * error) {
    
    // Login error
    NSLog(@" Login failed with exception: %@",[error errorDescription]);
    
}];
}

Make sure you replace the aut with your CometChat API Key in the above code.

📘

Sample Users

We have set up 5 users for testing having UIDs: SUPERHERO1, SUPERHERO2, SUPERHERO3, SUPERHERO4 and SUPERHERO5.

The login() method returns the User object containing all the information of the logged in user.

🚧

UID can be alphanumeric with underscore and hyphen. Spaces, punctuation and other special characters are not allowed.


Integrate our iOS UI Kit

Please refer iOS UI Kit section to integrate iOS UI Kit inside your app.


Integrate our iOS Chat Widget

Please refer to iOS Chat Widget section to integrate iOS Chat Widget inside your app.



Did this page help you?