CometChat Pro Documentation

You'll find comprehensive guides and documentation to help you start working with CometChat as quickly as possible. Let's jump right in!

iOS - APNs

Learn how to setup CometChat Pro Push Notifications using APNs

Apple Push Notification service or APNs is used to send notifications to iOS devices. With this, you can also use Apple's CallKit for showing the call screen.

I want to checkout the Sample app.

Click on the link below to check out our iOS Push Notifications Sample app.

Follow the steps mentioned in the README.md file.

View Sample App on GitHub

Get APNS Credentials

The following steps in this section are written on the assumption that you already have an app ID assigned to your client app.

Step 1: Create a Certificate Signing Request

To obtain a signing certificate required to sign apps for installation on iOS devices, you should first create a certificate signing request (CSR) file through Keychain Access on your Mac.

  1. Open the Keychain Access from the utility folder, go to Keychain Access > Certificate Assistant > Request a Certificate From a Certificate Authority, and then click.
  1. The Certificate Information dialog box appears. Enter the email address that you use in your Apple Developer account, and enter a common name for your private key. Don't enter CA email address, choose Saved to disk, and then click the Continue button.
  1. Specify the name of your CSR to save and choose the location to save the file on your local disk. Then your CSR file is created, which contains a public/private key pair.

Step 2: Create an SSL certificate

  1. Sign in to your account at the Apple Developer Member Center.
  2. Go to Certificates, Identifiers & Profiles.
  1. Create new Certificate by clicking on the + icon.
  1. Under Services, select - Apple Push Notification services SSL (Sandbox & Production)
  1. Select your App ID from the dropdown.
  1. Upload CSR file., upload the CSR file you created through the Choose File button. To complete the process, choose Continue. When the certificate is ready, choose Download to save it to your Mac.

Step 3: Export and update .p12 file

  1. Type a name for the .p12 file and save it to your Mac.
  2. Browse to the location where you saved your key, select it, and click Open. Add the key ID for the key (available in Certificates, Identifiers & Profiles in the Apple Developer Member Center) and export it.
  3. DO NOT provide an export password when prompted.
  4. The .p12 file will be required in the next step for uploading in the CometChat Pro Dashboard.

Extension Setup

Step 1: Enable the extension

  1. Login to the CometChat Dashboard.
  2. Select an existing app or create a new one.
  3. Go to the "Extensions" section and Enable the Push Notifications extension.
  4. Go to the "Installed" tab in the same section and open the settings for this extension.

Step 2: Save your Settings

Using only APNs as the provider

Using FCM and APNs

On the Settings page you need to enter the following:

  1. Set extension version
  • The extension version has to be set to 'V2' or 'V1 & V2' in order to use APNs as the provider.
  1. Select Platforms
  • You can select the platforms on which you wish to receive Push Notifications.
  1. Firebase Cloud Messaging Settings
  • This includes the FCM Server key that you can fetch from the Firebase Dashboard.
  1. APNs Settings
  • You can turn off the Production mode when you create a development build of your application.
  • Upload the .p12 certificate exported in the previous step.
  1. Push Notifications Title
  • This is usually the name of your app.
  1. Notification Triggers
  • Select the triggers for sending Push Notifications. These triggers can be classified into 3 main categories:
    -- Message Notifications
    -- Call Notifications
    -- Group Notifications
  • These are pretty self-explanatory and you can toggle them as per your requirement.

iOS App Setup

Initial Setup

  1. Call CometChat.init() method to initialize CometChat in your application. This needs to be called only once.
  2. The user has to be logged in using CometChat.login() method. On the success callback, register the token with the extension.
    Two tokens need to be registered, out of which one is APNs token and other is CallKit token:
    a. CometChat.registerTokenForPushNotification(token: apnsToken, settings: ["voip":false])
    b. CometChat.registerTokenForPushNotification(token: voipToken, settings: ["voip":true])
CometChat.login(UID: UID, apiKey: Constants.apiKey, onSuccess: { (current_user) in
        DispatchQueue.main.async {
          if let apnsToken = UserDefaults.standard.value(forKey: "apnsToken") as? String {
            print("APNS token is: \(apnsToken)")
            CometChat.registerTokenForPushNotification(token: apnsToken, settings: ["voip":false]) { (success) in
              print("onSuccess to registerTokenForPushNotification: \(success)")
              DispatchQueue.main.async {self.activityIndicator.stopAnimating()
                print("login success with : \(current_user.stringValue())")
                self.performSegue(withIdentifier: "presentPushNotification", sender: nil)
              }
            } onError: { (error) in
              print("error to registerTokenForPushNotification")
            }
          }
          if let voipToken = UserDefaults.standard.value(forKey: "voipToken") as? String {
            print("VOIP token is: \(voipToken)")
            CometChat.registerTokenForPushNotification(token: voipToken, settings: ["voip":true]) { (success) in
              print("onSuccess to registerTokenForPushNotification: \(success)")
              DispatchQueue.main.async {self.activityIndicator.stopAnimating()
                print("login success with : \(current_user.stringValue())")
                self.performSegue(withIdentifier: "presentPushNotification", sender: nil)
              }
            } onError: { (error) in
              print("error to registerTokenForPushNotification")
            }
          }
          }
        }
      }) { (error) in
        print("error while login", error);
      }
    }
  1. Import PushKit and CallKit in AppDelegate.Swift file.
import PushKit
import CallKit

Receive Push Notifications

  1. Registering for the APNs notifications
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {
self.voipRegistration()
// [START register_for_notifications]
    if #available(iOS 10.0, *) {
      UNUserNotificationCenter.current().delegate = self
      let authOptions: UNAuthorizationOptions = [.alert, .badge, .sound]
      UNUserNotificationCenter.current().requestAuthorization(
        options: authOptions,
        completionHandler: {_, _ in })
    } else {
      let settings: UIUserNotificationSettings =
        UIUserNotificationSettings(types: [.alert, .badge, .sound], categories: nil)
      application.registerUserNotificationSettings(settings)
    }
    application.registerForRemoteNotifications()
    // [END register_for_notifications]
    return true
}
  // Register for VoIP notifications
  func voipRegistration() {
    // Create a push registry object
    let mainQueue = DispatchQueue.main
    let voipRegistry: PKPushRegistry = PKPushRegistry(queue: mainQueue)
    voipRegistry.delegate = self
    voipRegistry.desiredPushTypes = [PKPushType.voIP]
  }
  1. Add AppDelegate extension for receiving Push Notifications
extension AppDelegate : UNUserNotificationCenterDelegate {
  // Receive displayed notifications for iOS 10 devices.
  func userNotificationCenter(_ center: UNUserNotificationCenter,
                willPresent notification: UNNotification,
                withCompletionHandler completionHandler: @escaping (UNNotificationPresentationOptions) -> Void) {
    print("willPresent notification: \(notification.request.content.userInfo)")
    if let userInfo = notification.request.content.userInfo as? [String : Any], let messageObject =
      userInfo["message"], let str = messageObject as? String, let dict = str.stringTodictionary() {
           if let baseMessage = CometChat.processMessage(dict).0 {
             switch baseMessage.messageCategory {
             case .message: 
              if let message = baseMessage as? BaseMessage {
                switch message.messageType {
                case .text:
                  print("text Messagge is: \((message as? TextMessage)?.stringValue())")
                case .image:
                  print("image Messagge is: \((message as? MediaMessage)?.stringValue())")
                case .video:
                  print("video Messagge is: \((message as? MediaMessage)?.stringValue())")
                case .audio:
                  print("audio Messagge is: \((message as? MediaMessage)?.stringValue())")
                case .file:
                  print("file Messagge is: \((message as? MediaMessage)?.stringValue())")
                case .custom:
                  print("custom Messagge is: \((message as? MediaMessage)?.stringValue())")
                case .groupMember:
                  break
                @unknown default:
                  break
                }
              }
             case .action: break
             case .call:
              if let call = baseMessage as? Call {
                print("call is: \(call.stringValue())")
              }
             case .custom:
              if let customMessage = baseMessage as? CustomMessage {
                print("customMessage is: \(customMessage.stringValue())")
              }
             @unknown default: break
             }
           }
         }
    completionHandler([.alert, .badge, .sound])
  }
  func userNotificationCenter(_ center: UNUserNotificationCenter,
                didReceive response: UNNotificationResponse,
                withCompletionHandler completionHandler: @escaping () -> Void) {
    let notification = response.notification.request.content.userInfo
    print("notification is 11: \(notification)")
    completionHandler()
  }
  func application(_ application: UIApplication, didRegisterForRemoteNotificationsWithDeviceToken deviceToken: Data) {
    let token = deviceToken.reduce("", {$0 + String(format: "%02X", $1)})
    print("Device Token : ",token)
    let hexString = deviceToken.map { String(format: "%02.2hhx", $0) }.joined()
    print("Device Token 11: ",hexString)
    UserDefaults.standard.set(hexString, forKey: "apnspuToken")
    CometChat.registerTokenForPushNotification(token: hexString, settings: ["voip":false]) { (success) in
      print("registerTokenForPushNotification voip: \(success)")
    } onError: { (error) in
      print("registerTokenForPushNotification error: \(error)")
    }
  }
}
  1. Add AppDelegate extension for VOIP notifications. Launch CallKit screen when the VOIP notification is received.
    Once the CallKit screen is displayed, you can Accept or Reject the CometChat call accordingly.
// MARK: CallKit & PushKit
extension AppDelegate: PKPushRegistryDelegate , CXProviderDelegate {
  func pushRegistry(_ registry: PKPushRegistry, didUpdate pushCredentials: PKPushCredentials, for type: PKPushType) {
    print("didUpdate : \(pushCredentials)")
    let deviceToken = pushCredentials.token.reduce("", {$0 + String(format: "%02X", $1) })
      print("voip token is: \(deviceToken)")
    UserDefaults.standard.set(deviceToken, forKey: "voipToken")
    CometChat.registerTokenForPushNotification(token: deviceToken, settings: ["voip":true]) { (success) in
      print("registerTokenForPushNotification voip: \(success)")
    } onError: { (error) in
      print("registerTokenForPushNotification error: \(error)")
    }
  }
  func pushRegistry(_ registry: PKPushRegistry, didReceiveIncomingPushWith payload: PKPushPayload, for type: PKPushType, completion: @escaping () -> Void) {
    print("didReceiveIncomingPushWith : \(payload.dictionaryPayload)")
    if let userInfo = payload.dictionaryPayload as? [String : Any], let messageObject =
      userInfo["message"], let dict = messageObject as? [String : Any] {
           if let baseMessage = CometChat.processMessage(dict).0 {
             switch baseMessage.messageCategory {
             case .message: break
             case .action: break
             case .call:
              if let call = baseMessage as? Call {
                switch call.callType {
                case .audio where call.receiverType == .user:
                  if let name = (call.sender)?.name {
                    let config = CXProviderConfiguration(localizedName: "")
                    config.iconTemplateImageData = imageLiteral(resourceName: "cometchat_white").pngData()
                    config.ringtoneSound = "ringtone.caf"
                    config.supportsVideo = false
                    let provider = CXProvider(configuration: config)
                    provider.setDelegate(self, queue: nil)
                    let update = CXCallUpdate()
                    update.remoteHandle = CXHandle(type: .generic, value: name)
                    update.hasVideo = false
                    provider.reportNewIncomingCall(with: UUID(), update: update, completion: { error in })
                  }
                case .audio where call.receiverType == .group:
                  if let group = (call.receiver as? Group)?.name {
                    let config = CXProviderConfiguration(localizedName: "APNS + Callkit")
                    config.iconTemplateImageData = imageLiteral(resourceName: "cometchat_white").pngData()
                    config.ringtoneSound = "ringtone.caf"
                    config.supportsVideo = false
                    let provider = CXProvider(configuration: config)
                    provider.setDelegate(self, queue: nil)
                    let update = CXCallUpdate()
                    update.remoteHandle = CXHandle(type: .generic, value: group)
                    update.hasVideo = false
                    provider.reportNewIncomingCall(with: UUID(), update: update, completion: { error in })
                  }
                case .video where call.receiverType == .user:
                  if let name = (call.sender)?.name {
                    let config = CXProviderConfiguration(localizedName: "APNS + Callkit")
                    config.iconTemplateImageData = imageLiteral(resourceName: "cometchat_white").pngData()
                    config.ringtoneSound = "ringtone.caf"
                    config.supportsVideo = true
                    let provider = CXProvider(configuration: config)
                    provider.setDelegate(self, queue: nil)
                    let update = CXCallUpdate()
                    update.remoteHandle = CXHandle(type: .generic, value: name)
                    update.hasVideo = true
                    provider.reportNewIncomingCall(with: UUID(), update: update, completion: { error in })
                  }
                case .video where call.receiverType == .group:
                  if let group = (call.receiver as? Group)?.name {
                    let config = CXProviderConfiguration(localizedName: "APNS + Callkit")
                    config.iconTemplateImageData = imageLiteral(resourceName: "cometchat_white").pngData()
                    config.ringtoneSound = "ringtone.caf"
                    config.supportsVideo = true
                    let provider = CXProvider(configuration: config)
                    provider.setDelegate(self, queue: nil)
                    let update = CXCallUpdate()
                    update.remoteHandle = CXHandle(type: .generic, value: group)
                    update.hasVideo = true
                    provider.reportNewIncomingCall(with: UUID(), update: update, completion: { error in })
                  }
                case .audio: break
                case .video: break
                @unknown default: break
                }
                print("call is: \(call.stringValue())")
              }
             case .custom:
              if let customMessage = baseMessage as? CustomMessage {
                print("customMessage is: \(customMessage.stringValue())")
              }
             @unknown default: break
             }
           }
         }
  }
  func providerDidReset(_ provider: CXProvider) {
  }
  func provider(_ provider: CXProvider, perform action: CXAnswerCallAction) {
    // Perform Start Call
    action.fulfill()
  }
  func provider(_ provider: CXProvider, perform action: CXEndCallAction) {
    // Perform End Call
    action.fulfill()
  }
}

Advanced

Convert Push Notification payload to Message object

CometChat pro SDK provides a method CometChat.CometChatHelper.processMessage() which will take the JSON received in The push notification as input, and return the corresponding TextMessage, MediaMessage,CustomMessage or Call object in return. Once the message object is received, you can use the entity as per your requirements.

This code needs to be added to the willPresent notification method of the UNUserNotificationCenterDelegate delegate.

func userNotificationCenter(_ center: UNUserNotificationCenter,
                                willPresent notification: UNNotification,
                                withCompletionHandler completionHandler: @escaping (UNNotificationPresentationOptions) -> Void) {
        if let userInfo = notification.request.content.userInfo as? [String : Any], let messageObject = userInfo["message"], let str = messageObject as? String, let dict = str.stringTodictionary() {

   if let baseMessage = CometChat.processMessage(dict).0 {
     switch baseMessage.messageCategory {
      case .message: 
        if let message = baseMessage as? BaseMessage {
          switch message.messageType {
             case .text:
                print("text Messagge is: \((message as?TextMessage)?.stringValue())")
             case .image:
                 print("image Messagge is: \((message as? MediaMessage)?.stringValue())")
             case .video:
                 print("video Messagge is: \((message as? MediaMessage)?.stringValue())")
              case .audio:
                 print("audio Messagge is: \((message as? MediaMessage)?.stringValue())")
              case .file:
                  print("file Messagge is: \((message as? MediaMessage)?.stringValue())")
               case .custom:
                   print("custom Messagge is: \((message as? MediaMessage)?.stringValue())")
               case .groupMember: break
               @unknown default:break}
              }
            case .action: break
             case .call:
               if let call = baseMessage as? Call {
                  print("call is: \(call.stringValue())")
                }
               case .custom:
                  if let customMessage = baseMessage as? CustomMessage {
                    print("customMessage is: \(customMessage.stringValue())")
                 }
                 @unknown default: break
              }
             }
            }
        completionHandler([.alert, .badge, .sound])
 }

extension String {
  func stringTodictionary() -> [String:Any]? {
        var dictonary:[String:Any]?
                if let data = self.data(using: .utf8) {
                    do {
        dictonary = try JSONSerialization.jsonObject(with: data, options: []) as? [String : Any]
                if let myDictionary = dictonary
        {
          return myDictionary;
        }
      } catch let error as NSError {
        print(error)
      }
            }
    return dictonary;
  }
}

Updated 14 days ago


iOS - APNs


Learn how to setup CometChat Pro Push Notifications using APNs

Suggested Edits are limited on API Reference Pages

You can only suggest edits to Markdown body content, but not to the API spec.