Skip to main content
Quick Reference for AI Agents & Developers
  • Requires: CometChat SDK and UI Kit both configured
  • Implementation: Handle notification tap in AppDelegate or SceneDelegate
  • Parse payload: Extract sender UID or group GUID from notification payload
  • Launch: Present CometChatMessages view controller with user/group
  • Related: Receive Message · Push Notifications · UI Kit
This guide helps you to launch a chat window from the UI Kit library on receiving a new message notification.
CometChat SDK & UI Kit both need to be configured before launching the chat window.

Step 1. Process push notification payload and grab User or Group object

To present a chat window, firstly you will need a User or a Group object. You can grab this from the push notification payload itself of incoming message notification. You need to call CometChat.processMessage() method to process push notification payload.
 func userNotificationCenter(_ center: UNUserNotificationCenter,
                    didReceive response: UNNotificationResponse,
                    withCompletionHandler completionHandler: @escaping () -> Void) {
        
        if let userInfo = response.notification.request.content.userInfo as? [String : Any], let messageObject = userInfo["message"] as? [String:Any] {
           print("didReceive: \\(userInfo)")
          if let baseMessage = CometChat.processMessage(messageObject).0 {
            switch baseMessage.messageCategory {
            case .message:
                print("Message Object Received: \\(String(describing: (baseMessage as? TextMessage)?.stringValue()))")
                
            case .action: break
            case .call: break
            case .custom: break
            @unknown default: break
            }
          }
        }
        completionHandler()
      }
userInfo Dictionary Structure (User Message):
ParameterTypeDescription
message[String: Any]Message dictionary containing message details. See message Dictionary below
aps[String: Any]Apple Push Notification Service payload. See aps Dictionary below
message Dictionary:
ParameterTypeDescription
idIntUnique message identifier. Example: 12345
muidStringMessage unique ID. Example: "muid_xyz123"
categoryStringMessage category. Example: "message"
typeStringMessage type. Example: "text"
textStringMessage content. Example: "Hello there!"
sender[String: Any]Sender user details. See sender Dictionary below
receiverStringReceiver UID. Example: "cometchat-uid-2"
receiverTypeStringReceiver type. Example: "user"
sentAtIntUnix timestamp. Example: 1699800000
deliveredAtIntDelivery timestamp. Example: 0
readAtIntRead timestamp. Example: 0
conversationIdStringConversation ID. Example: "cometchat-uid-1_user_cometchat-uid-2"
sender Dictionary:
ParameterTypeDescription
uidStringSender’s unique ID. Example: "cometchat-uid-1"
nameStringSender’s display name. Example: "Andrew Joseph"
avatarStringSender’s avatar URL. Example: "https://example.com/avatar.png"
statusStringUser online status. Example: "online"
roleStringUser role. Example: "default"
lastActiveAtIntLast active timestamp. Example: 1699799000
aps Dictionary:
ParameterTypeDescription
alert[String: Any]Alert content. See alert Dictionary below
badgeIntBadge count. Example: 1
soundStringNotification sound. Example: "default"
mutable-contentIntEnables notification modification. Example: 1
alert Dictionary:
ParameterTypeDescription
titleStringNotification title. Example: "Andrew Joseph"
bodyStringNotification body. Example: "Hello there!"
userInfo Dictionary Structure (Group Message):
ParameterTypeDescription
message[String: Any]Message dictionary containing message details. See message Dictionary below
aps[String: Any]Apple Push Notification Service payload. See aps Dictionary below
message Dictionary:
ParameterTypeDescription
idIntUnique message identifier. Example: 12346
muidStringMessage unique ID. Example: "muid_abc456"
categoryStringMessage category. Example: "message"
typeStringMessage type. Example: "text"
textStringMessage content. Example: "Hey team!"
sender[String: Any]Sender user details. See sender Dictionary below
receiver[String: Any]Receiver group details. See receiver Dictionary below
receiverTypeStringReceiver type. Example: "group"
sentAtIntUnix timestamp. Example: 1699800000
deliveredAtIntDelivery timestamp. Example: 0
readAtIntRead timestamp. Example: 0
conversationIdStringConversation ID. Example: "group_cometchat-guid-1"
sender Dictionary:
ParameterTypeDescription
uidStringSender’s unique ID. Example: "cometchat-uid-1"
nameStringSender’s display name. Example: "Andrew Joseph"
avatarStringSender’s avatar URL. Example: "https://example.com/avatar.png"
statusStringUser online status. Example: "online"
roleStringUser role. Example: "default"
lastActiveAtIntLast active timestamp. Example: 1699799000
receiver Dictionary (Group):
ParameterTypeDescription
guidStringGroup’s unique ID. Example: "cometchat-guid-1"
nameStringGroup’s display name. Example: "Development Team"
iconStringGroup’s icon URL. Example: "https://example.com/group.png"
typeStringGroup type. Example: "public"
membersCountIntNumber of members. Example: 15
ownerStringGroup owner UID. Example: "cometchat-uid-1"
createdAtIntCreation timestamp. Example: 1699700000
hasJoinedBoolWhether user has joined. Example: true
aps Dictionary:
ParameterTypeDescription
alert[String: Any]Alert content. See alert Dictionary below
badgeIntBadge count. Example: 1
soundStringNotification sound. Example: "default"
mutable-contentIntEnables notification modification. Example: 1
alert Dictionary:
ParameterTypeDescription
titleStringNotification title. Example: "Development Team"
bodyStringNotification body. Example: "Andrew Joseph: Hey team!"
Method Signature:
ParameterTypeDescription
Input[String: Any]Push notification message dictionary
Returns(BaseMessage?, CometChatException?)Tuple containing parsed message or error
Return Tuple Structure:
IndexTypeDescription
0BaseMessage?Parsed message object. See TextMessage Object below
1CometChatException?Error object if parsing fails. nil on success
TextMessage Object Properties (when type is “text”):
ParameterTypeDescription
idIntMessage ID. Example: 12345
muidStringMessage unique ID. Example: "muid_xyz123"
messageCategoryMessageCategoryCategory enum. Example: .message
messageTypeMessageTypeType enum. Example: .text
textStringMessage text content. Example: "Hello there!"
senderUserSender user object. See sender Object below
receiverUser or GroupReceiver object. See receiver Object below
receiverTypeReceiverTypeType of receiver. Example: .user or .group
sentAtIntUnix timestamp. Example: 1699800000
deliveredAtIntDelivery timestamp. Example: 0
readAtIntRead timestamp. Example: 0
conversationIdStringConversation identifier. Example: "cometchat-uid-1_user_cometchat-uid-2"
editedAtIntEdit timestamp. Example: 0
editedByString?Editor UID. Example: nil
deletedAtIntDeletion timestamp. Example: 0
deletedByString?Deleter UID. Example: nil
sender User Object:
ParameterTypeDescription
uidStringUser’s unique ID. Example: "cometchat-uid-1"
nameStringUser’s display name. Example: "Andrew Joseph"
avatarString?User’s avatar URL. Example: "https://example.com/avatar.png"
statusUserStatusOnline status. Example: .online
roleStringUser role. Example: "default"
lastActiveAtIntLast active timestamp. Example: 1699799000
receiver Object (User or Group):When receiverType is .user:
ParameterTypeDescription
uidStringUser’s unique ID. Example: "cometchat-uid-2"
nameStringUser’s display name. Example: "Jane Smith"
avatarString?User’s avatar URL. Example: "https://example.com/avatar2.png"
statusUserStatusOnline status. Example: .offline
When receiverType is .group:
ParameterTypeDescription
guidStringGroup’s unique ID. Example: "cometchat-guid-1"
nameStringGroup’s display name. Example: "Development Team"
iconString?Group’s icon URL. Example: "https://example.com/group.png"
groupTypeGroupTypeGroup type. Example: .public
membersCountIntNumber of members. Example: 15
MessageCategory Enum Values:
ValueDescription
.messageRegular message (text, media, etc.)
.actionAction message (member joined, left, etc.)
.callCall message
.customCustom message type
ReceiverType Enum Values:
ValueDescription
.userOne-to-one conversation
.groupGroup conversation

Step 2. Launch Chat Window

You can launch the chat window from your base view controller after you tap on the Message Notification. This method uses NotificationCenter to trigger and present a chat window.
  1. In this method you need to fire notification after you receive the User or Group Object.
  2. In Notification’s user info you can pass User or Group Object to that desired notification.

Trigger notification from App Delegate

if let message = baseMessage as? BaseMessage {
  switch baseMessage.receiverType {
    case .user:
     DispatchQueue.main.asyncAfter(deadline: .now() + 0.5) {
       if let user = baseMessage.sender {
         NotificationCenter.default.post(name: NSNotification.Name(rawValue: "didReceivedMessageFromUser"), object: nil, userInfo: ["user":user])
       }
     }
    case .group:
    DispatchQueue.main.asyncAfter(deadline: .now() + 0.5) {
      if let group = baseMessage.receiver as? Group {
        NotificationCenter.default.post(name: NSNotification.Name(rawValue: "didReceivedMessageFromGroup"), object: nil, userInfo: ["group":group])
       }
      }
    @unknown default: break
  }
}
NotificationCenter.default.post() Method Parameters:
ParameterTypeDescription
nameNSNotification.NameNotification identifier name. Example: NSNotification.Name(rawValue: "didReceivedMessageFromUser")
objectAny?Sender object (typically nil). Example: nil
userInfo[AnyHashable: Any]?Dictionary containing user data. See userInfo Dictionary below
userInfo Dictionary Structure:
ParameterTypeDescription
userUserThe sender User object. See User Object below
User Object Properties:
ParameterTypeDescription
uidStringUser’s unique ID. Example: "cometchat-uid-1"
nameStringUser’s display name. Example: "Andrew Joseph"
avatarString?User’s avatar URL. Example: "https://example.com/avatar.png"
linkString?User’s profile link. Example: nil
statusUserStatusOnline status. Example: .online
roleStringUser role. Example: "default"
lastActiveAtIntLast active timestamp. Example: 1699799000
hasBlockedMeBoolWhether user has blocked current user. Example: false
blockedByMeBoolWhether current user has blocked this user. Example: false
metadata[String: Any]?Custom metadata. Example: nil
tags[String]?User tags. Example: []
UserStatus Enum Values:
ValueDescription
.onlineUser is currently online
.offlineUser is offline
.availableUser is available
Notification Dispatch Flow:
StepActionDescription
1Check receiverTypebaseMessage.receiverType == .user
2Extract senderbaseMessage.sender
3DelayDispatchQueue.main.asyncAfter(deadline: .now() + 0.5)
4PostNotificationCenter.default.post(...)
NotificationCenter.default.post() Method Parameters:
ParameterTypeDescription
nameNSNotification.NameNotification identifier name. Example: NSNotification.Name(rawValue: "didReceivedMessageFromGroup")
objectAny?Sender object (typically nil). Example: nil
userInfo[AnyHashable: Any]?Dictionary containing group data. See userInfo Dictionary below
userInfo Dictionary Structure:
ParameterTypeDescription
groupGroupThe receiver Group object. See Group Object below
Group Object Properties:
ParameterTypeDescription
guidStringGroup’s unique ID. Example: "cometchat-guid-1"
nameStringGroup’s display name. Example: "Development Team"
iconString?Group’s icon URL. Example: "https://example.com/group.png"
descriptionString?Group description. Example: "Team discussions"
groupTypeGroupTypeGroup type. Example: .public
membersCountIntNumber of members. Example: 15
ownerStringGroup owner UID. Example: "cometchat-uid-1"
createdAtIntCreation timestamp. Example: 1699700000
updatedAtIntLast update timestamp. Example: 1699750000
hasJoinedBoolWhether current user has joined. Example: true
joinedAtIntJoin timestamp. Example: 1699710000
scopeMemberScopeCurrent user’s scope. Example: .participant
metadata[String: Any]?Custom metadata. Example: nil
tags[String]?Group tags. Example: []
GroupType Enum Values:
ValueDescription
.publicAnyone can join
.privateRequires invitation
.passwordRequires password to join
MemberScope Enum Values:
ValueDescription
.adminAdministrator privileges
.moderatorModerator privileges
.participantRegular member
Notification Dispatch Flow:
StepActionDescription
1Check receiverTypebaseMessage.receiverType == .group
2Extract receiverbaseMessage.receiver as? Group
3DelayDispatchQueue.main.asyncAfter(deadline: .now() + 0.5)
4PostNotificationCenter.default.post(...)
  1. On the other hand, you need to observe for the above notification in your base view controller.
  1. Base view controller is a controller that launches immediately after the app delegate.
  2. Base view controller should be present to observe the notification when notification fires.
  3. If the view controller is not present in the memory when a new notification receives, then it won’t launch Chat Window.

Observe notification in Base View Controller

class BaseViewController : UIViewController {
  
  override func viewDidLoad() {
   NotificationCenter.default.addObserver(self, selector:#selector(self.didReceivedMessageFromGroup(_:)), name: NSNotification.Name(rawValue: "didReceivedMessageFromGroup"), object: nil)
        NotificationCenter.default.addObserver(self, selector:#selector(self.didReceivedMessageFromUser(_:)), name: NSNotification.Name(rawValue: "didReceivedMessageFromUser"), object: nil)
  }
}

Add selector method & Launch Chat Window

  @objc func didReceivedMessageFromGroup(_ notification: NSNotification) {
        if let group = notification.userInfo?["group"] as? Group {
            DispatchQueue.main.async {
             let messageList = CometChatMessageList()
             let navigationController = UINavigationController(rootViewController:messageList)
              messageList.set(conversationWith: group, type: .group)
              self.present(navigationController, animated:true, completion:nil)
            }
        }
    }
    
    @objc func didReceivedMessageFromUser(_ notification: NSNotification) {
          print("didReceivedMessageFromUser")
        if let user = notification.userInfo?["user"] as? User {
            DispatchQueue.main.async {
             let messageList = CometChatMessageList()
             let navigationController = UINavigationController(rootViewController:messageList)
              messageList.set(conversationWith: user, type: .user)
              self.present(navigationController, animated:true, completion:nil)
            }
        }
    }
NSNotification Object Structure:
ParameterTypeDescription
nameNSNotification.NameNotification identifier. Example: "didReceivedMessageFromGroup"
objectAny?Sender object. Example: nil
userInfo[AnyHashable: Any]?Dictionary containing group data. See userInfo Dictionary below
userInfo Dictionary:
ParameterTypeDescription
groupGroupThe Group object from notification. See Group Object below
Group Object Properties:
ParameterTypeDescription
guidStringGroup’s unique ID. Example: "cometchat-guid-1"
nameStringGroup’s display name. Example: "Development Team"
iconString?Group’s icon URL. Example: "https://example.com/group.png"
descriptionString?Group description. Example: "Team discussions"
groupTypeGroupTypeGroup type. Example: .public
membersCountIntNumber of members. Example: 15
ownerStringGroup owner UID. Example: "cometchat-uid-1"
createdAtIntCreation timestamp. Example: 1699700000
hasJoinedBoolWhether current user has joined. Example: true
scopeMemberScopeCurrent user’s scope. Example: .participant
CometChatMessageList Configuration:
ParameterTypeDescription
set(conversationWith:type:)(Group, ReceiverType)Method to set group conversation
set(conversationWith:type:) Parameters:
ParameterTypeDescription
conversationWithGroupThe Group object to open conversation with
typeReceiverTypeReceiver type. Example: .group
Selector Method Flow:
StepActionDescription
1Extractnotification.userInfo?["group"] as? Group
2DispatchDispatchQueue.main.async { ... }
3Initializelet messageList = CometChatMessageList()
4WrapUINavigationController(rootViewController: messageList)
5ConfiguremessageList.set(conversationWith: group, type: .group)
6Presentself.present(navigationController, animated: true)
NSNotification Object Structure:
ParameterTypeDescription
nameNSNotification.NameNotification identifier. Example: "didReceivedMessageFromUser"
objectAny?Sender object. Example: nil
userInfo[AnyHashable: Any]?Dictionary containing user data. See userInfo Dictionary below
userInfo Dictionary:
ParameterTypeDescription
userUserThe User object from notification. See User Object below
User Object Properties:
ParameterTypeDescription
uidStringUser’s unique ID. Example: "cometchat-uid-1"
nameStringUser’s display name. Example: "Andrew Joseph"
avatarString?User’s avatar URL. Example: "https://example.com/avatar.png"
linkString?User’s profile link. Example: nil
statusUserStatusOnline status. Example: .online
roleStringUser role. Example: "default"
lastActiveAtIntLast active timestamp. Example: 1699799000
hasBlockedMeBoolWhether user has blocked current user. Example: false
blockedByMeBoolWhether current user has blocked this user. Example: false
CometChatMessageList Configuration:
ParameterTypeDescription
set(conversationWith:type:)(User, ReceiverType)Method to set user conversation
set(conversationWith:type:) Parameters:
ParameterTypeDescription
conversationWithUserThe User object to open conversation with
typeReceiverTypeReceiver type. Example: .user
Selector Method Flow:
StepActionDescription
1Extractnotification.userInfo?["user"] as? User
2DispatchDispatchQueue.main.async { ... }
3Initializelet messageList = CometChatMessageList()
4WrapUINavigationController(rootViewController: messageList)
5ConfiguremessageList.set(conversationWith: user, type: .user)
6Presentself.present(navigationController, animated: true)