Initial configuration

Before building your chat app, you must initialize and configure the Chat SDK.

Start by signing into the Admin Portal or creating an account if you don't have one yet.

Then, create an app on the Admin Portal. You will need a PubNub app to get a keyset that consists of a Subscribe Key and a Publish Key. These keys will let you establish a connection between PubNub and the chat app you're going to create with the Chat SDK.

When you create a new app on the Admin Portal, the first set of demo keys is generated automatically, but a single app can have as many keysets as you like. We recommend that you create separate keysets for production and test environments.

Enable features on your keyset

Each keyset has its own configuration settings in the Admin Portal. To use some features in your chat app, you must enable appropriate settings on your app's keyset on the Admin Portal.

To use the Chat SDK, create or update users, track presence, and store messages in history, you must to enable App Context, Presence, and Message Persistence on your keyset.

Download the SDK

Download the SDK from any of the following sources:

Use Swift Package Manager

To integrate PubNub into your project using the Swift Package Manager specify PubNub in the dependencies list of your Package.swift file:

dependencies: [
.package(url: "https://github.com/pubnub/swift-chat-sdk", exact: "0.8.0-dev")
]

Use Xcode

  1. Create or open your project inside Xcode.
  2. Navigate to File -> Add Package Dependencies.
  3. Search for https://github.com/pubnub/swift-chat-sdk.
  4. From the Dependency Rule drop-down list, select Exact. In the version input field, type 0.8.0-dev.
  5. Click the Add Package button.

Initialize PubNub

Once you have a PubNub account and an app created on the Admin Portal, you can start initializing PubNub Client API context and establish account-level credentials.

To initialize PubNub with the Chat SDK:

  1. Create a ChatImpl object, which takes the following parameters:

    ConfigurationDescription
    pubNubConfigurationAn instance of the PubNub account configuration. You must provide at least the subscribeKey and userId to connect to PubNub.
    chatConfigurationAn instance of chat-specific configuration required to implement advanced features, like typing indicator, user offline/online presence, push notifications, or client-side limiting that prevents spamming.
  2. Call the initialize() method on your ChatImpl object.

// Chat SDK-specific configuration
public struct ChatConfiguration {
public var logLevel: LogLevel
public var typingTimeout: Int
public var storeUserActivityInterval: Int
public var storeUserActivityTimestamps: Bool
public var pushNotificationsConfig: PushNotificationsConfig
public var rateLimitFactor: Int
public var rateLimitPerChannel: [ChannelType: Int64]
public var customPayloads: CustomPayloads?

public init(
logLevel: LogLevel = .off,
typingTimeout: Int = 5,
storeUserActivityInterval: Int = 600,
show all 38 lines

Input parameters

ParameterTypeDescription
pubNubConfigurationPubNubConfigurationMandatory PubNub account configuration.
  → publishKeyStringSpecifies the key used to publish messages on a channel.
 → subscribeKeyStringSpecifies the key used to subscribe to a channel.
 → userIdStringUnique User ID that becomes your app's current user. It's a string of up to 92 characters that identifies a single client (end user, device, or server) that connects to PubNub. Based on User ID, PubNub calculates pricing for your apps' usage. User ID should be persisted and remain unchanged. If you don't set userId, you won't be able to connect to PubNub.
chatConfigurationChatConfigurationChatConfiguration contains chat app configuration settings, such as saveDebugLog or typingTimeout that you provide when initializing your chat app with the initialize() method. You can later directly access these properties, like: chat.storeUserActivityInterval.

ChatConfiguration

ParameterTypeRequiredDefaultFeatureDescription
logLevelLogLevelNo.offError loggingSpecifies if any Chat SDK-related errors should be logged. It's disabled by default. Available options include: off, error, warn, info, debug, and verbose.
typingTimeoutIntNo5Typing IndicatorSpecifies the default timeout after which the typing indicator automatically stops when no typing signals are received. The default and maximum value is set to 5 seconds.
storeUserActivityIntervalIntNo600User's last online activity, global presenceSpecifies how often the user global presence in the app should be updated. Requires storeUserActivityTimestamps to be set to true. The default value is set to 60 seconds, and that's the minimum possible value. If you try to set it to a lower value, you'll get the storeUserActivityInterval must be at least 60000ms error.
storeUserActivityTimestampsBoolNofalseUser's last online activity, global presenceSpecifies if you want to track the user's global presence in your chat app. The user's activity is tracked through the lastActiveTimestamp parameter on the User object.
pushNotificationsConfigPushNotificationsConfigNon/aPush NotificationsList of parameters you must set if you want to enable sending/receiving mobile push notifications for phone devices, either through Apple Push Notification service (APNS) or Firebase Cloud Messaging (FCM).
 → sendPushesBoolNofalseas aboveThe main option for enabling sending notifications. It must be set to true if you want a particular client (whether a mobile device, web browser, or server) to send push notifications to mobile devices.

These push notifications are messages with a provider-specific payload that the Chat SDK automatically attaches to every message. Chat SDK includes a default payload setup for deviceGateway in every message sent to the registered channels.

This is the only required option to enable if you want to send push notifications to Android devices. For iOS devices, you also have to configure apnsTopic.
 → deviceTokenStringNon/aas aboveOption for receiving notifications on iOS and Android devices.

A device token refers to the unique identifier assigned to a specific mobile device by a platform's push notification service. It targets and delivers push notifications to the intended app on that specific device. Suppose you don't set this option and try to run channel registration-related methods. In that case, you'll get the Device Token has to be defined in Chat pushNotifications config error.

Refer to the official Apple and Google docs to learn how to obtain a device token for the APNs and FCM services.
 → deviceGatewayPubNub.PushServiceNofcmas aboveOption for receiving push notifications on Android (fcm or gcm) or iOS (apns or apns2) devices. These are the available types:

  • apns - Apple Push Notification service
  • apns2 - Apple Push Notification service v2
  • fcm - Firebase Cloud Messaging
  • gcm - Google Cloud Messaging (deprecated)
 → apnsTopicStringNon/aas aboveAn Apple specific-option for sending and receiving notifications.

This string is a bundle ID that you must define yourself for your iOS app so that Apple could enable push notifications for it in APNs. The string takes the following format: com.domainname.applicationname. Apple combines that ID with your Team ID (generated by Apple) and creates an App ID for your application.

To send pushes from an iOS device, you must also set sendPushes to true. To receive pushes on an iOS device, you must also set deviceGateway to apns2, define deviceToken, and apnsEnvironment. Suppose you don't configure apnsTopic, but set deviceGateway to apns2. In that case, you'll get the apnsTopic has to be defined when deviceGateway is set to apns2 error and Chat SDK won't attach the apns payload to messages.
 → apnsEnvironmentPubNub.PushEnvironmentNodevelopmentas aboveOption for receiving notifications on iOS devices. When registering for push notifications, this option specifies whether to use the development (development) or production (production) APNs environment.
rateLimitFactorIntNo2Client-side rate limitingThe so-called "exponential backoff" which multiplicatively decreases the rate at which messages are published on channels.

It's bound to the rateLimitPerChannel parameter and is meant to prevent message spamming caused by excessive retries.

The default value of 2 means that if you set rateLimitPerChannel for direct channels to 1 second and try to send three messages on such a channel type within the span of one second, the second message will be published one second after the first one (just like the rateLimitPerChannel value states), but the third one will be published two seconds after the second one, meaning the publishing time is multiplied by 2.
rateLimitPerChannel[ChannelType: Int64]Non/aClient-side rate limitingClient-side limit that states the rate at which messages can be published on a given channel type. Its purpose is to prevent message spamming in your chat app.

This parameter takes an object with these three parameters: direct, group, and public.
 → directIntNo0 (no limit)as aboveRate set on all direct (1:1) channels at which messages can be published.
 → groupIntNo0 (no limit)as aboveRate set on all group channels at which messages can be published.
 → publicIntNo0 (no limit)as aboveRate set on all public channels at which messages can be published.
 → unknownIntNo0 (no limit)as aboveRate set on all channels created using the Swift SDK instead of Swift Chat SDK.
customPayloadsCustomPayloadsNon/aSend and receive messagesProperty that lets you define your custom message payload to be sent and/or received by Chat SDK on one or all channels, whenever it differs from the default message.text Chat SDK payload.

It also lets you configure your own message actions whenever a message is edited or deleted.

For examples, check Custom payload.
 → getMessagePublishBodyFunction that takes three parameters:
  • EventContent.TextMessageContent object
  • String representing a channel ID
  • DefaultGetMessagePublishBody representing a default handler
Non/aas aboveFunction that lets Chat SDK send your custom payload structure. It defines the structure of your own message payload's body (of any type) that you're sending through PubNub.

Expand the Message-related types section for more details on the required TextMessageContent structure.

Define getMessageResponseBody whenever you use getMessagePublishBody.
 → getMessageResponseBodyFunction that takes three parameters:
  • JSONCodable representing the message response
  • String representing a channel ID
  • DefaultGetMessageResponseBody representing a default handler
Non/aas aboveFunction that lets Chat SDK receive your custom payload structure. Use it to let Chat SDK translate your custom message payload into the default Chat SDK message format (defined in EventContent.TextMessageContent).

Expand the Message-related types section for more details on the required EventContent.TextMessageContent structure.

Define getMessagePublishBody whenever you use getMessageResponseBody.
 → editMessageActionNameStringNon/aas aboveA type of action you want to be added to your Message object whenever a published message is edited, like "changed" or "modified".

The default message action used by Chat SDK is "edited".

Expand the Message-related types section for more details.
 → deleteMessageActionNameStringNon/aas aboveA type of action you want to be added to your Message object whenever a published message is deleted, like "removed".

The default message action used by Chat SDK is "deleted".

Expand the Message-related types section for more details.

Additional configuration options

Since the Chat SDK heavily relies on the latest Swift SDK for all the underlying methods, when initializing the Chat SDK client, you can also make use of all optional parameters that come with the Swift SDK.

For example, you can decide how long the server will consider the client alive for presence (presenceTimeout) or how often the client will announce itself to the server (heartbeatInterval).

For the whole list of all such inherited optional parameters which you can define when initializing the Chat SDK instance, check the Swift SDK configuration document.

Basic usage

Required setup

Use this basic example to initialize the client setting only the required parameters.

// Create PubNub configuration
let pubNubConfiguration = PubNubConfiguration(
publishKey: "your-publish-key",
subscribeKey: "your-subscribe-key",
userId: "your-user-id"
// Add other required parameters
)

// Create Chat configuration
let chatConfiguration = ChatConfiguration(
// Fill in the necessary parameters for ChatConfiguration
)

// Create ChatImpl instance
let yourChat = ChatImpl(
show all 28 lines

Typing indicator timeout

Initialize the PubNub Chat SDK and set the default typing indicator timeout value to three seconds.

// Create PubNub configuration
let pubNubConfiguration = PubNubConfiguration(
publishKey: "your-publish-key",
subscribeKey: "your-subscribe-key",
userId: "your-user-id"
// Add other required parameters
)

// Create Chat configuration
let chatConfiguration = ChatConfiguration(
typingTimeout: 3
)

// Create ChatImpl instance
let yourChat = ChatImpl(
show all 28 lines

Client-side rate limiting

Initialize the PubNub Chat SDK and set the hard limit for message publishing on public channels to three seconds. If there are more publish retries within this limit, each next retry limit should be multiplied by 3.

// Create PubNub configuration
let pubNubConfiguration = PubNubConfiguration(
publishKey: "your-publish-key",
subscribeKey: "your-subscribe-key",
userId: "your-user-id"
// Add other required parameters
)

// Create Chat configuration
let chatConfiguration = ChatConfiguration(
rateLimitFactor: 3,
rateLimitPerChannel: [
.public: Int64(3 * 1000) // 3 seconds converted to milliseconds
]
)
show all 31 lines

Custom payload

When initializing Chat SDK, you can pass your custom message payload structure using the customPayloads object and related properties. This will let Chat SDK correctly interpret your app's messages when sending and receiving them.

Define custom payload for all channels

Let's say your app doesn't follow the default message.text message body structure imposed by Chat SDK but instead uses the my.custom.payload.structure.text structure.

To successfully communicate with PubNub and send/receive messages through Chat SDK, pass your custom payload to all channels. Additionally, define your custom action names to be added to messages when they're edited or deleted.

// Define custom payloads
let customPayloads = CustomPayloads(
getMessagePublishBody: { content, _, _ in
return [
"custom": [
"payload": [
"text": content.text
]
// Optionally also save files as ["files": content.files]
]
]
},
getMessageResponseBody: { json, _, _ in
guard
let custom = try? json.decode([String: AnyJSON].self),
show all 54 lines
Define custom payload for one channel

Let's say your app doesn't follow the default message.text message body structure imposed by Chat SDK for support-channel but instead uses the my.custom.payload.structure.text structure to communicate with PubNub.

Pass your custom payload to support-channel to successfully communicate with PubNub and send/receive messages through Chat SDK. Additionally, define your custom action names to be added to messages when they're edited or deleted.

The code sets up a PubNub chat instance with specific handlers for processing message payloads differently based on the channel.

// Define custom payloads
let customPayloads = CustomPayloads(
getMessagePublishBody: { content, channelId, defaultHandler in
if channelId == "support-channel" {
return [
"my": [
"custom": [
"payload": [
"structure": content.text
]
]
],
// Optional parameter
"files": content.files as Any,
] as [String: Any]
show all 68 lines

Next steps

Now that you've initialized and configured the Chat SDK, you can start creating channels, adding users, and powering your app with all sorts of features.

Last updated on