Appearance
Push & Notifications
About 812 wordsAbout 3 min
Swift SDK - Chat API
Table of Contents
- Push Configuration - APN
- Push Configuration - Firebase
- AppDelegate Setup
- Register Device
- Remove Device
- List Devices
- Handling Incoming Push
- Notification Content Extension
- Badge Count Management
Push Configuration - APN
Configure push notifications using Apple Push Notification service (APN). Set up the APN configuration on the ChatClientConfig to enable push delivery for chat messages.
Example
import StreamChat
var config = ChatClientConfig(apiKeyString: "YOUR_API_KEY")
config.pushNotifications.apnConfiguration = .init(
teamId: "<your_team_id>",
bundleId: Bundle.main.bundleIdentifier!
)
let client = ChatClient(config: config)
client.connectUser(
userInfo: UserInfo(id: "john"),
token: .init(stringLiteral: "<user_token>")
)Push Configuration - Firebase
Configure push notifications using Firebase Cloud Messaging (FCM). Set up the Firebase configuration on the ChatClientConfig to enable Firebase-based push delivery.
Example
import StreamChat
var config = ChatClientConfig(apiKeyString: "YOUR_API_KEY")
config.pushNotifications.firebaseConfiguration = .init(
serverKey: "<your_firebase_server_key>"
)
let client = ChatClient(config: config)
client.connectUser(
userInfo: UserInfo(id: "john"),
token: .init(stringLiteral: "<user_token>")
)AppDelegate Setup
Set up your AppDelegate to handle push notification registration and forward the device token to the Stream Chat SDK.
Example
import UIKit
import StreamChat
class AppDelegate: UIResponder, UIApplicationDelegate {
let config = ChatClientConfig(apiKeyString: "YOUR_API_KEY")
lazy var client = ChatClient(config: config)
func application(
_ application: UIApplication,
didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?
) -> Bool {
UNUserNotificationCenter.current().requestAuthorization(
options: [.alert, .badge, .sound]
) { granted, error in
if granted {
DispatchQueue.main.async {
application.registerForRemoteNotifications()
}
}
}
client.connectUser(
userInfo: UserInfo(id: "john"),
token: .init(stringLiteral: "<user_token>")
)
return true
}
func application(
_ application: UIApplication,
didRegisterForRemoteNotificationsWithDeviceToken deviceToken: Data
) {
client.currentUserController().addDevice(token: deviceToken) { error in
if let error = error {
print("Failed to register device: \(error)")
}
}
}
func application(
_ application: UIApplication,
didFailToRegisterForRemoteNotificationsWithError error: Error
) {
print("Failed to register for push notifications: \(error)")
}
}Register Device
Register a device for push notifications. Use addDevice(token:) on the CurrentUserController to register the APN device token.
Example
import StreamChat
let config = ChatClientConfig(apiKeyString: "YOUR_API_KEY")
let client = ChatClient(config: config)
client.connectUser(
userInfo: UserInfo(id: "john"),
token: .init(stringLiteral: "<user_token>")
)
let controller = client.currentUserController()
// Register with APN device token
let deviceToken: Data = ... // from didRegisterForRemoteNotificationsWithDeviceToken
controller.addDevice(token: deviceToken) { error in
if let error = error {
print("Failed to add device: \(error)")
} else {
print("Device registered for push notifications")
}
}Remove Device
Remove a registered device to stop receiving push notifications. Use removeDevice(id:) on the CurrentUserController with the device identifier.
Example
import StreamChat
let config = ChatClientConfig(apiKeyString: "YOUR_API_KEY")
let client = ChatClient(config: config)
client.connectUser(
userInfo: UserInfo(id: "john"),
token: .init(stringLiteral: "<user_token>")
)
let controller = client.currentUserController()
// Remove device by its identifier
controller.removeDevice(id: "<device_id>") { error in
if let error = error {
print("Failed to remove device: \(error)")
} else {
print("Device removed from push notifications")
}
}List Devices
List all registered devices for the current user. Use the currentUserController to access devices and manage registrations.
Example
import StreamChat
let config = ChatClientConfig(apiKeyString: "YOUR_API_KEY")
let client = ChatClient(config: config)
client.connectUser(
userInfo: UserInfo(id: "john"),
token: .init(stringLiteral: "<user_token>")
)
let controller = client.currentUserController()
controller.synchronize { error in
guard error == nil else { return }
let devices = controller.currentUser?.devices ?? []
for device in devices {
print("Device ID: \(device.id)")
print("Created at: \(device.createdAt)")
}
}Handling Incoming Push
Handle incoming chat push notifications by parsing the notification payload. Use ChatPushNotificationInfo to extract channel and message information from the push payload.
Example
import StreamChat
import UserNotifications
class NotificationService: UNNotificationServiceExtension {
let config = ChatClientConfig(apiKeyString: "YOUR_API_KEY")
lazy var client = ChatClient(config: config)
override func didReceive(
_ request: UNNotificationRequest,
withContentHandler contentHandler: @escaping (UNNotificationContent) -> Void
) {
let content = request.content
// Parse the Stream push notification
guard let info = try? ChatPushNotificationInfo(content: content) else {
contentHandler(content)
return
}
// Access notification details
print("Channel CID: \(info.cid)")
print("Message ID: \(info.messageId)")
// Modify notification content if needed
let mutableContent = content.mutableCopy() as! UNMutableNotificationContent
mutableContent.title = info.title ?? "New Message"
mutableContent.body = info.body ?? ""
contentHandler(mutableContent)
}
}Notification Content Extension
Create a notification content extension to display rich chat message previews in push notifications. Use ChatChannelController to load message details for the notification.
Example
import UIKit
import StreamChat
import StreamChatUI
import UserNotifications
import UserNotificationsUI
class NotificationViewController: UIViewController, UNNotificationContentExtension {
let config = ChatClientConfig(apiKeyString: "YOUR_API_KEY")
lazy var client = ChatClient(config: config)
func didReceive(_ notification: UNNotification) {
guard let info = try? ChatPushNotificationInfo(
content: notification.request.content
) else { return }
// Connect as the recipient
client.connectUser(
userInfo: UserInfo(id: "<recipient_id>"),
token: .init(stringLiteral: "<user_token>")
)
// Load the channel to display message context
let channelController = client.channelController(for: info.cid)
channelController.synchronize { [weak self] error in
guard error == nil else { return }
// Display the channel name and latest message
let channelName = channelController.channel?.name ?? "Chat"
self?.title = channelName
}
}
}Badge Count Management
Manage the app badge count based on unread messages. Use currentUserController to observe total unread count and update the badge accordingly.
Example
import UIKit
import StreamChat
class BadgeManager: ChatCurrentUserControllerDelegate {
let config = ChatClientConfig(apiKeyString: "YOUR_API_KEY")
lazy var client = ChatClient(config: config)
lazy var controller = client.currentUserController()
func setup() {
client.connectUser(
userInfo: UserInfo(id: "john"),
token: .init(stringLiteral: "<user_token>")
)
controller.delegate = self
controller.synchronize()
}
func currentUserController(
_ controller: ChatCurrentUserController,
didChangeCurrentUserUnreadCount unreadCount: UnreadCount
) {
DispatchQueue.main.async {
UIApplication.shared.applicationIconBadgeNumber = unreadCount.messages
}
}
}
// Usage
let badgeManager = BadgeManager()
badgeManager.setup()