Skip to main content

Reference implementation

UIKit iOS push sample (APNs + PushKit/CallKit).

What this guide covers

  • CometChat dashboard setup (enable push, add APNs Device + APNs VoIP providers) with screenshots.
  • APNs + PushKit/CallKit wiring (tokens, delegates, CallKit).
  • Incoming message/call handling and deep links.
  • Payload customization and testing.

What you need first

  • CometChat App ID, Region, Auth Key; Push Notifications with APNs Device provider ID and APNs VoIP provider ID.
  • Apple capabilities: Push Notifications, Background Modes (Remote notifications, Voice over IP), CallKit usage descriptions. Physical device required.
  • .p8 APNs key (Key ID, Team ID, Bundle ID) or certificates.

1. Enable push and add providers (CometChat dashboard)

  1. Go to Notifications → Settings and enable Push Notifications.
Enable Push Notifications
  1. Click Add Credentials:
    • Add an APNs Device provider (alerts) using your .p8 key, Team ID, Key ID, and Bundle ID; copy the Provider ID.
    • Add an APNs VoIP provider (calls) with the same .p8 (recommended for CallKit reliability); copy the Provider ID.
Add APNs credentials
Keep the provider IDs—you’ll paste them into your app constants.

2. Apple setup

  1. Capabilities: Push Notifications, Background Modes → Remote notifications & Voice over IP, CallKit usage descriptions in Info.plist (mic/camera).
  2. APNs Auth Key: generate .p8 (or use cert), note Key ID, Team ID, and Bundle ID; upload to CometChat providers.
Enable Push Notifications and Background Modes for APNs

3. Wiring APNs + PushKit/CallKit

  • Copy CometChatAPNsHelper.swift, CometChatPNHelper.swift, and the two AppDelegate extensions (AppDelegate+PN.swift and AppDelegate+VoIP.swift) into your project.
  • These files implement APNs + PushKit/CallKit handling, notification presentation, tap and quick-reply actions, and call management.
  • Update bundle ID, team ID, and provider IDs (AppConstants.PROVIDER_ID etc.). Keep the voip push type.
import Foundation
import UIKit
import CometChatSDK
import CometChatUIKitSwift

extension AppDelegate: UNUserNotificationCenterDelegate {
    
    // MARK: - Foreground Notifications
    func userNotificationCenter(_ center: UNUserNotificationCenter, willPresent notification: UNNotification, withCompletionHandler completionHandler: @escaping (UNNotificationPresentationOptions) -> Void) {
        print("willPresent notification: \(notification.request.content.userInfo)")
        let userInfo = notification.request.content.userInfo
        
        if CometChatPNHelper.shouldPresentNotification(userInfo: userInfo) == false {
            print("Suppressing notification (user is in active chat)")
            completionHandler([])
            return
        }
        
        completionHandler([.banner, .badge, .sound])
    }

    // MARK: - Notification Tap/Interaction
    func userNotificationCenter(_ center: UNUserNotificationCenter, didReceive response: UNNotificationResponse, withCompletionHandler completionHandler: @escaping () -> Void) {
        
        let userInfo = response.notification.request.content.userInfo
        print("User tapped notification: \(userInfo)")

        if response.actionIdentifier == "REPLY_ACTION" {
            if let textResponse = response as? UNTextInputNotificationResponse {
                let userReply = textResponse.userText
                print("Quick reply: \(userReply)")
                CometChatPNHelper.handleQuickReplyActionOnNotification(userInfo: userInfo, text: userReply, completionHandler: completionHandler)
            }
            completionHandler()
            return
        }
        
        CometChatPNHelper.handleTapActionOnNotification(userInfo: userInfo, completionHandler: completionHandler)
    }
}

4. Register APNs device + VoIP tokens with CometChat

  • In your AppDelegate.swift, implement the following methods to handle APNs registration success and failure, and to register the device token with CometChat.
  • Make sure to import the necessary modules at the top of the file.
  • Complete your AppDelegate.swift as shown below:
import UIKit
import PushKit
import CometChatSDK
import CometChatUIKitSwift

@main
class AppDelegate: UIResponder, UIApplicationDelegate {

    var window: UIWindow?
    var pushRegistry: PKPushRegistry?
    let cometchatAPNsHelper = CometChatAPNsHelper()
    func application(
        _ application: UIApplication,
        didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?
    ) -> Bool {
        
        UNUserNotificationCenter.current().delegate = self
        
        cometchatAPNsHelper.configurePushNotification(application: application, delegate: self)
        
        // Initialize PushKit
        initializePushKit()

        return true
    }
    
    // MARK: - APNs Registration Success
    func application(_ application: UIApplication, didRegisterForRemoteNotificationsWithDeviceToken deviceToken: Data) {
        print("APNs Device token received!")
        
        if CometChat.getLoggedInUser() != nil {
            print("User is logged in, registering APNs token...")
            cometchatAPNsHelper.registerTokenForPushNotification(deviceToken: deviceToken)
        } else {
            print("User NOT logged in yet, will register token after login")
            // Store token for later registration
            let hexString = deviceToken.map { String(format: "%02.2hhx", $0) }.joined()
            UserDefaults.standard.set(hexString, forKey: "pendingAPNsToken")
        }
    }
    
    // MARK: - APNs Registration Failure
    func application(_ application: UIApplication, didFailToRegisterForRemoteNotificationsWithError error: Error) {
        print("Failed to register for APNs: \(error.localizedDescription)")
    }
}

5. Testing checklist

  1. Install on a device; grant notification permission. Verify APNs device token logs.
  2. Log in, then confirm both device + VoIP tokens register with CometChat (success callbacks).
  3. Send a message from another user:
    • Foreground: ensure willPresent shows your chosen presentation.
    • Background/terminated: tapping opens the correct conversation.
  4. Trigger an incoming call; CallKit UI should show caller info. Accept should join the call; Decline should reject via CometChat and end CallKit.
  5. Rotate tokens (reinstall or toggle VoIP) to ensure re-registration works.

6. Troubleshooting

SymptomQuick checks
No pushesEntitlements set, APNs provider creds correct, bundle ID matches dashboard, permission granted.
Token registration failsRun after login; provider IDs correct for device vs VoIP.
Taps do nothingVerify notification center delegate and navigation readiness before routing.
Call UI missingEnsure PushKit delegate fires, CallKit capabilities enabled, VoIP provider ID set.
Audio errorsConfigure AVAudioSession for playAndRecord when reporting/accepting calls.