Business Messaging Client Side v2
Business Messaging
Version 2

Track notification events

Copy link

Sendbird Business Messaging offers comprehensive tracking capabilities for both in-app messages and push notifications, extending the application of Business Messaging including the Sequence functionality.

Business Messaging allows you to track viewed and clicked events for in-app messages and delivered and clicked for push notifications. This is essential for some of Business Messaging's features, such as:

  • Sequence: Send a message through various channels based on the event.
  • User insights: Monitor message's status through the events per user.
  • Analytics: Analyze the channel like Click rates, opened rates, etc.

In-app notifications

Copy link

Viewed

Copy link

This event indicates that the user has viewed the notification. This event is crucial for tracking user engagement and interaction with messages. Call the FeedChannel.logViewed function when you consider that the user has viewed the notification. The exact conditions may vary depending on your business requirements.

The following code snippets demonstrate the implementation for the logViewed function in Kotlin, Swift, and JavaScript.

KotlinSwiftJavaScript
fun logViewed(channel: FeedChannel, visibleMessages: List<BaseMessage>) {
    val result = channel.logViewed(visibleMessages)
    if (result) {
        // Success
    } else {
        // Error
    }
}

UIKit Handling of logViewed Event

Copy link

Unlike the SDK, Sendbird Business Messaging UIKit automatically handles the viewed event for you through the FeedChannel.logViewed function. For example, let's look at the scenarios in which the function is called within our UIKit. The function is called when:

  1. the message list on the screen changes due to actions such as entering the first screen, changing the category filter, or in any cases where the message screen has to be re-rendered.
  2. the current user's scrolling stops - with a delay of 0.5 seconds.
  3. in all cases, the list of currently visible messages, not all messages in the channel, on the screen is passed to logViewed().

Thus the UIKit can minimize the effort of tracking the viewed event manually. However, if a manual implementation of event tracking is necessary in your client app, you can use the SDK and its logViewed function as shown in the code snippets above.

Clicked

Copy link

Click events are critical to track to gauge user interaction with the content. A message is marked as clicked when a user interacts with it, such as selecting a message or tapping a link or button within a message. The methods below should be used when a message is clicked and is considered to have been clicked by a user.

KotlinSwiftJavaScript
fun logClicked(channel: FeedChannel, clickedMessage: BaseMessage) {
    val result = channel.logClicked(clickedMessage)
    if (result) {
        // Success
    } else {
        // Error
    }
}

Push notifications

Copy link

For Business Messaging to accurately track push notification events, push notifications must be correctly set up in your mobile application. Sendbird provides the detailed guides for configuring push notifications on both Android and iOS.

Set up environment for Android

Copy link

To integrate push notifications with Sendbird on Android, follow the guide for setting up push notifications for Firebase Cloud Messaging (FCM). This setup includes creating a Firebase project, configuring your app with Firebase, adding Firebase configuration files to your project, and integrating FCM with the Sendbird SDK.

For a step-by-step guide, see our documentation on Push notifications for SDK.

This guide will walk you through the steps to ensure your Android application can receive and process push notifications, pivotal for tracking delivered and clicked events within your app.

Track delivered

Copy link

If you've implemented SendbirdPushHelper and registered message events in SendbirdPushHandler during the push notification setup, a delivered event is automatically tracked when a user receives a push notification.

Track clicked

Copy link

Similar to in-app messages, tracking when a push notification is clicked provides insights into how users interact with notifications and which message prompts an action.

The following two code snippets demonstrate the implementation for click event tracking.

Ship the data to the pending intent of the notification

Copy link
class YourFirebaseMessagingService : SendbirdPushHandler() {
    override fun onMessageReceived(remoteMessage: RemoteMessage) {
        // create redirect target Intent
        // the remoteMessage is the value passed to the onMessageReceived function.
        val remoteMessageData = HashMap(remoteMessage.data)
        val targetIntent = Intent(context, TARGET_INTENT::class.java).apply {
            // set other values..
            putExtra("PUSH_NOTIFICATION_DATA", remoteMessageData)
        }

        // create target pending Intent to launch when the notification is clicked.
        @SuppressLint("UnspecifiedImmutableFlag")
        val pending intent = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            PendingIntent.getActivity(
                context,
                YOUR_REQUEST_CODE,
                targetIntent,
                PendingIntent.FLAG_IMMUTABLE
            )
        } else {
            PendingIntent.getActivity(context, messageId.toInt(), intent, 0)
        }

        // Fill the `tag`, `channelId`, `channelName`, and `notificationId`
        val tag = "NOTIFICATION TAG"
        val channelId = "YOUR CHANNEL ID"
        val channelName = "YOUR CHANNEL NAME"
        val notificationId = YOUR_NOTIFICATION_ID
        val notificationManager = context.getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            NotificationChannel(channelId, channelName, NotificationManager.IMPORTANCE_HIGH).let {
                notificationManager.createNotificationChannel(it)
            }
        }

        // send notification
        val notificationBuilder = NotificationCompat.Builder(context, channelId)
            // .. other settings
            .setContentIntent(pendingIntent)
        notificationManager.notify(tag, notificationId, notificationBuilder.build())
    }
}

Call the markPushNotificationAsClicked method

Copy link

Call markPushNotificationAsClicked method in the Activity that runs when the Push banner is clicked. This allows you to track a click event on the notification.

class YourActivity : Activity() {
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        // .. set other configuration
        sendMarkNotificationAsClicked(intent)
    }
    override fun onNewIntent(intent: Intent?) {
        super.onNewIntent(intent)
        sendMarkNotificationAsClicked(intent)
    }

    // This key must match with the extra key of Notification pending intent
    private val PUSH_NOTIFICATION_DATA = "PUSH_NOTIFICATION_DATA"
    private fun sendMarkNotificationAsClicked(intent: Intent?) {
        intent?.let {
            if (intent.hasExtra(PUSH_NOTIFICATION_DATA)) {
                intent.getSerializable(PUSH_NOTIFICATION_DATA, HashMap::class.java)?.let { hashMap ->
                    val data: Map<String, String> = hashMap.mapNotNull {
                        if (it.key is String && it.value is String) {
                            it.key as String to it.value as String
                        } else {
                            null
                        }
                    }.toMap()
                    SendbirdPushHelper.markPushNotificationAsClicked(data)
                }
                // You must delete it after use so that it is not reused on the next run.
                intent.removeExtra(PUSH_NOTIFICATION_DATA)
            }
        }
    }
}

Set up environment for iOS

Copy link

For iOS, setting up push notifications involves registering your app with the Apple Push Notification service (APNs), configuring your app's notification settings, and integrating these settings with the Sendbird SDK. This process ensures your iOS app is prepared to handle push notifications, allowing for effective tracking within the Business Messaging feature.

Detailed instructions can be found on our guide for push notifications for SDK.

This comprehensive guide provides the steps to configure your iOS application to receive push notifications from APNs and how to communicate these notifications to the Sendbird servers for tracking purposes.

Track delivered

Copy link

To mark a push notification as delivered when received, follow the instructions below:

  1. Make sure to set the app group in AppDelegate when initializing the SendbirdChat SDK.

  2. Implement the necessary method in the NotificationServiceExtension as demonstrated below.

class NotificationService: UNNotificationServiceExtension {
    var contentHandler: ((UNNotificationContent) -> Void)?
    var bestAttemptContent: UNMutableNotificationContent?
    
    override func didReceive(
        _ request: UNNotificationRequest, 
        withContentHandler contentHandler: @escaping (UNNotificationContent) -> Void
    ) {
        self.bestAttemptContent = (request.content.mutableCopy()
              as? UNMutableNotificationContent)

        if let bestAttemptContent = bestAttemptContent {
            SendbirdChat.setAppGroup("YOUR_APP_ID")
            SendbirdChat.markPushNotificationAsDelivered(
                remoteNotificationPayload: bestAttemptContent.userInfo
            ) { error in
                
            }
           
            // Always call the completion handler when done.
            contentHandler(bestAttemptContent)
        }    
    }
    // ...
}

Note: Sendbird SDK marks a push notification as delivered when receiving it from AppDelegate regardless of whether the client app is in the foreground or background. This ensures that the notification is delivered even if a user does't see the push banner. If your client app can receive a push notification in the foreground but doesn't want to display it, add a condition called markPushNotificationAsDelivered method so that it does not deliver in the foreground.

Track clicked

Copy link

Similar to in-app messages, tracking when a push notification is clicked provides insights into how users interact with notifications and which messages prompt action. Implement the userNotificationCenter (_:didReceive:withCompletionHandler:) method in AppDelegate. This is called when a user clicks on a push notification.

class AppDelegate: UIResponder, UIApplicationDelegate, UNUserNotificationCenterDelegate {
    // ...
    public func userNotificationCenter(_ center: UNUserNotificationCenter,
            didReceive response: UNNotificationResponse,
            withCompletionHandler completionHandler: @escaping () -> Swift.Void) {
        let userInfo = response.notification.request.content.userInfo

        SendbirdChat.markPushNotificationAsClicked(remoteNotificationPayload: userInfo)
        // ...
    }
    // ...
}