Notifications

Last Edit: May 05 2020

Stream Dashboard Setup

You need to setup Push Notifications in Stream Dashboard. Please check docs.

Stream's helper singleton, Notifications.shared, is only available in StreamChatCore.

Push Notifications Template for APN


{
    "aps": {
        "alert": {
            "title": "{{ sender.name }} @ {{ channel.name }}",
            "body": "{{ message.text }}"
        },
        "badge": {{ unread_count }},
        "category": "NEW_MESSAGE",
        "sound": "default"
    },
    "channel_id": "{{ channel.id }}",
    "channel_type": "{{ channel.type }}",
    "message_id": "{{ message.id }}"
}
                    

Local Notifications Template

To set custom templates for local notifications, you need to set Notifications.shared.localNotificationContent block. When a local notification arrives, this block will be called to generate UNNotificationContent.

You need to set this in a single place, like your AppDelegate:


import StreamChatCore

func application(_ application: UIApplication,
                 didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {
    Notifications.shared.localNotificationContent = { message, channel in
        let content = UNMutableNotificationContent()
        content.title = "\(message.user.name) @ \(channel.name ?? "")"
        content.body = message.text
        content.sound = UNNotificationSound.default
       content.badge = (UIApplication.shared.applicationIconBadgeNumber + 1) as NSNumber
       return content
    }
    
    return true
}
                    

Your Project Settings

You need to enable Push Notifications capability in your project settings to make it work.

User Notifications Permissions

To make notifications works you have to ask a user for notifications permissions. If you're handling notification permissions yourself, or only using StreamChatClient, you can skip directly to "User Device" part. Stream provides helper functions to help developers gain time in this process, you can use these helper functions but you don't have to.

Onboarding

Usually, apps have an onboarding to prepare users for permissions, because if he denied permissions for the first time, then another way to enable permissions will be to ask the user to change notifications permissions in Settings.

When a user is ready to setup permissions you can call:


Notifications.shared.askForPermissions()
                    

Regular Launch

On each time when your app is started and a user passed an onboarding you can call:


Notifications.shared.askForPermissionsIfNeeded()
                    

⚠️ If a user changed notifications permissions in Settings you need to call askForPermissionsIfNeeded() again.

User Device

Add a User Device

We need to register a user device for push notifications. Add this code to add a device to a user:


func application(_ application: UIApplication, didRegisterForRemoteNotificationsWithDeviceToken deviceToken: Data) {
    Client.shared.addDevice(deviceToken: deviceToken)
    // or
    Client.shared.addDevice(deviceToken: deviceToken) { (result) in /* Handle result */ }
}
                    

Remove a User Device

When a user logged out you need to unregister his device before that to avoid sending push notifications to his old device:


let deviceId = User.current.devices.last!.id
Client.shared.removeDevice(deviceId: deviceId)
                    

Handle Push Notifications

Setup push notifications handler in your AppDelegate to navigate a user to your chat screen with a new message:


Notifications.shared.onNewMessage = { messageReference in
    // Show a ChatViewController with a given messageReference.
    print("Push notification received for ", 
        messageReference.channelType,
        messageReference.channelId,
        messageReference.messageId,)
}
                    

This could be useful to get a MessageReference from a notification in your delegate:Notifications.parseMessageReference(response: notificationResponse) (docs)

You can enable automatically clear application icon badge when your app becomes active:


Notifications.shared.clearApplicationIconBadgeNumberOnAppActive = true