iOS

This tutorial tell us how to add Chat Widget to your iOS application.

Before getting started

Go through the introduction to set up Chat Widget from the CometChat Dashboard

I want to integrate Chat Widget in my App

  1. Installation
  2. Initialize
  3. Login
  4. Launch

The Chat Widget is ready to use a chat UI based framework that can easily integrate into your app within a just few minutes.

Installation

1. Add the CometChatWidget Dependency

Open a terminal window, move to your project directory, and then create a Podfile by running the following command.

pod init

Add the following lines to the Podfile.

platform :ios, '11.0'
use_frameworks!

target 'MyApp' do
  pod 'CometChatProWidget', '3.0.1-1'
end

And then install the CometChatPro framework through CocoaPods.

pod install

Or

pod install --repo-update

2. Add Authorization Permissions

Prepare your app for this requirement by providing justification strings. The justification string is a localizable message that you add to your app's Info.plist file to tell the user why your app needs access to the user's photo library, Camera, Microphone. Then, App prompts the user to grant permission for access, the alert displays the justification string you provided, in the language of the locale selected on the user's device. You can do this as follows:

<key>NSAppTransportSecurity</key>
  <dict>
      <key>NSAllowsArbitraryLoads</key>
      <true />
  </dict>
<key>NSCameraUsageDescription</key>
    <string>$(PRODUCT_NAME) need access to the camera in order to update your avatar</string>
<key>NSPhotoLibraryUsageDescription</key>
    <string>$(PRODUCT_NAME) need access to the Photo Library in order to send Media Messages</string>
<key>NSMicrophoneUsageDescription</key>
    <string>$(PRODUCT_NAME) need access to the Microphone in order to connect Audio/Video call </string>
<key>NSLocationWhenInUseUsageDescription</key>
    <string>$(PRODUCT_NAME) need access to the Location services in order to share your location </string>

Initialize CometChatWidget

The init() method initializes the settings required for CometChatWidget. We suggest you call the method on app startup preferably in the didFinishLaunchingWithOptions: method of the AppDelegate class. Also, you need to add this method in the Application class whenever the app enters in foreground to maintain real-time connectivity.

import UIKit
import CometChatProWidget

@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
 
// App Lifecycle: didFinishLaunchingWithOptions
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {
     self.initializeWidget()
     return true
}
    
// App Lifecycle: applicationWillEnterForeground  
func applicationWillEnterForeground(_ application: UIApplication) {
     self.initializeWidget()
}

      
private func initializeWidget(){
 let _ = CometChatWidget.init(appID: "Enter APP ID", region:  "Enter Region Code", authKey: "Enter AuthKey", onSuccess: { (success) in
                                                                                     
       print("CometChatWidget initialized successfully \(success)")
                                                                                     
    }) { (error) in
           
       print("Error occurred during CometChatWidget Initialization \(error.errorDescription)")
        
}  
}
#import "AppDelegate.h"
#import <CometChatProWidget/CometChatProWidget-Swift.h>

@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
 
@interface AppDelegate ()

@end
// App Lifecycle: didFinishLaunchingWithOptions
@implementation AppDelegate


- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
    [self initializeWidget];
    return YES;
}
    
// App Lifecycle: applicationWillEnterForeground  
- (void)applicationWillEnterForeground:(UIApplication *)application {
   [self initializeWidget]; 
}

      
-(void) initializeWidget {
    [[CometChatWidget alloc] initWithAppID: @"Enter APP ID" region: @"Enter Region Code" authKey:@"Enter Auth Key" onSuccess:^(BOOL success) {
      
        NSLog(@"CometChatWidget initialized successfully %id",success);
      
    } onError:^(CometChatException * _Nonnull error) {
      
        NSLog(@"Error occurred during CometChatWidget Initialization %@",error);
      
    }];
  }
}

Register or Update User

To create or update users on the fly, you can use the createOrUpdate(user:) method. This method takes a User object as an input parameter and returns the created or updated User object if the request is successful.

import CometChatPro
import CometChatProWidget

let user = User(uid: "Enter UID", name: "Enter User name")

CometChatWidget.createOrUpdateUser(user: User) { (user) in
                                            
    print("User is: \(user.stringValue())") 
                                            
   } onError: { (error) in
               
    print("error is: \(error)")
               
}
#import <CometChatProWidget/CometChatProWidget-Swift.h>
#import <CometChatPro/CometChatPro-Swift.h>

User *user = [[User alloc]initWithUid:@"Enter UID" name:@"Enter Name"];

[CometChatWidget createOrUpdateWithUser:user onSuccess:^(User * _Nonnull user) {
  
        NSLog(@"User is %@",user);
  
    } onError:^(CometChatException * _Nonnull error) {
  
        NSLog(@"Error is %@",error.errorDescription);

}];

Login User

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

CometChatWidget.login(with: "Enter UID") { (user) in
                                          
   print("User is: \(user.stringValue())")
                                          
  } onError: { (error) in
              
   print("error is: \(error)")  
}
[CometChatWidget loginWith:@"Enter UID" onSuccess:^(User * _Nonnull user) {
   
        NSLog(@"User is: %@",user);
   
   } onError:^(CometChatException * _Nonnull error) {
   
        NSLog(@"Error is: %@",error.errorDescription);
 
  }];

Launch CometChatWidget

To launch CometChatWidget you need to create a constructor of WidgetSettings class. You can create this constructor using two ways.

let widgetSettings = WidgetSettings(widgetID: "Enter WidgetID", defaultID: "Enter DefaultID", receiverType: .user)
WidgetSettings *widgetSettings = [[WidgetSettings alloc] initWithWidgetID:@"Enter Widget ID" defaultID:@"Enter Default ID" receiverType:ReceiverTypeUser];

WidgetSettings class takes the following parameters:

No

Parameters

Information

widgetID

The unique identifier for widget

defaultID

default ID is the UID or GUID of the user to launch chat window directly when the sidebar is turned off.

receiverType

The type of the receiver to launch chat window directly when the sidebar is turned off. i.e user or group

Or

let widgetSettings = WidgetSettings(widgetID: "Enter WidgetID", entity: User Object)
WidgetSettings *widgetSettings = [[WidgetSettings alloc] initWithWidgetID:@"Enter Widget ID" entity:ReceiverTypeUser];

WidgetSettings class takes the following parameters:

No

Parameters

Information

widgetID

The unique identifier for widget

entity

The entity of the receiver to to launch chat window directly when the sidebar is turned off. i.e User or Group Object

After creating constructor, pass it to launch(widgetSettings:) method. This method launches the window and returns success when the widget launches.

CometChatWidget.launch(widgetSettings: widgetSettings) { (success) in
    
    print("CometChatWidget launched successfully \(success)")
                                                        
   } onError: { (error) in
           
    print("Error occurred during CometChatWidget launch \(error.errorDescription)")  
}
[CometChatWidget launchWithWidgetSettings:widgetSettings onSuccess:^(BOOL success) {
     NSLog(@"CometChatWidget launched successfully: %id",success);
  
  } onError:^(CometChatException * _Nonnull error) {
  
     NSLog(@"Error occurred during CometChatWidget launch: %id",error.errorDescription);
  
}];

Launch Chat Window for User

You can launch a user's chat window directly by passing uid of the user.

CometChatWidget.chatWithUser(uid: "ENTER UID HERE") { (success) in
  
      print("Chat Window launched successfully \(success)")
            
 } onError: { (errpr) in

      print("Error occurred during Chat Window launch \(error.errorDescription)")
 
 }
[CometChatWidget chatWithUserWithUid:@"Enter UID HERE" onSuccess:^(BOOL success) {
        
        NSLog(@"Chat Window launched successfully: %id",success);
        
    } onError:^(CometChatException * _Nonnull error) {
        
        NSLog(@"Error occurred during Chat window launch: %@",error);
    }];

Launch Chat Window for Group

You can launch a group's chat window directly by passing guid of the group.

CometChatWidget.chatWithGroup(guid: "ENTER  GUID HERE") { (success) in
  
      print("Chat Window launched successfully \(success)")
            
 } onError: { (errpr) in

      print("Error occurred during Chat Window launch \(error.errorDescription)")
 
 }
[CometChatWidget chatWithGroupWithGuid:@"Enter GUID HERE" onSuccess:^(BOOL success) {
        NSLog(@"Chat Window launched successfully: %id",success);
  
    } onError:^(CometChatException * _Nonnull error) {
        
        NSLog(@"Error occurred during Chat window launch: %@",error);
    }];

Create or Update Group

Additionally, if you want to create or update group and launch a direct chat with a particular conversation then you can use createOrUpdate(group:) method. This method returns the Group Object which you can pass in widgetSettings directly and launch the chat window.

let group = Group(guid: "Enter GUID", name: "Enter Group Name", groupType: .public, password: nil, icon: "Icon URL", description: "Enter Group Description")
  
CometChatWidget.createOrUpdateGroup(group: Group) { (group) in
   
   print("Group is: \(group.stringValue())")   
                                              
   } onError: { (error) in
               
    print("error is: \(error.errorDescription)") 
               
 }
Group *group = [[Group alloc] initWithGuid:@"Enter GUID" name:@"Enter Group Name" groupType:groupTypePublic password:nil icon:@"Icon URL" description:@"Group Description"];
    
[CometChatWidget createOrUpdateWithGroup:group onSuccess:^(Group * _Nonnull group) {
   NSLog(@"Group is %@",group.stringValue);
  
  } onError:^(CometChatException * _Nonnull error) {
  
    NSLog(@"error is %@",error.errorDescription);
  
 }];

Logout

you can use thelogout method to remove user session which is currently logged in inside the app.

CometChatWidget.logout { (success) in
                        
   print("User logged out successfully: \(success)")    
                        
   } onError: { (error) in
               
   print("error is: \(error.errorDescription)")      
               
}
[CometChatWidget logoutOnSuccess:^(BOOL success) {
    
  NSLog(@"User logged out successfully:%id",success);
  
 } onError:^(CometChatException * _Nonnull error) {
   
  NSLog(@"error is %@",error.errorDescription);
  
}];

Publishing to App Store

To publish your App on App Store please follow this guide


Did this page help you?