Skip to main content

Messaging

Prerequisites

Follow the setup instructions at Product Guide > Messaging

Ensure you have set up a Messaging Service, such as Firebase Cloud Messaging.

Additional Configuration

This App requires some additional configuration, if you would like to send out push notifications:

Frontend (Mobile)

If you wish to use DashX's messaging features to send notifications:

  • Add your iOS app on Firebase Console: Project Overview > Add App > iOS

  • Download GoogleService-Info.plist

  • Add GoogleService-Info.plist using XCode by right clicking on project and select Add Files, select your downloaded file and make sure Copy items if needed is checked.

  • In your Podfile add this:

pod 'DashX'
  • Implement the DashXAppDelegate
import DashX
import FirebaseCore
import FirebaseMessaging

@main
class AppDelegate: DashXAppDelegate {

...

func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {
DashX.configure(
withPublicKey: '...',
)

// Initialize Firebase and FCM
FirebaseApp.configure()
Messaging.messaging().delegate = self

// Request permission for push notifications and handle the resulting authorization status
DashX.requestNotificationPermission { authorizationStatus in
switch authorizationStatus {
case .authorized:
// User has granted permission for push notifications
case .denied:
// User has denied permission for push notifications
case .notDetermined:
// User has not yet made a choice about push notifications
case .provisional:
// User has granted provisional permission for push notifications (iOS 12+)
@unknown default:
// Handle any future authorization status not accounted for in the switch statement
}
}

// This method registers the device token with DashX
DashX.subscribe()

return true
}

override func notificationDeliveredInForeground(message: [AnyHashable: Any]) -> UNNotificationPresentationOptions {
print("\n=== Notification Delivered In Foreground ===\n")
print(message)
print("\n=================================================\n")

// This is how you want to show your notification in the foreground
// You can pass "[]" to not show the notification to the user or
// handle this with your own custom styles
return [.sound, .alert, .badge]
}

override func notificationClicked(message: [AnyHashable: Any], actionIdentifier: String) {
print("\n=== Notification Clicked ===\n")
print(message)

// Get the required data from the notification message
let userId = message["USER_ID"] as! String

// Perform the task associated with the action.
switch actionIdentifier {
case "ACCEPT_ACTION": APIManager.accept(userId: userId)
case "DECLINE_ACTION": APIManager.decline(userId: userId)
// handle other actions
default: break
}

print("\n=================================\n")
}
}
  • Disable swizzling for Firebase

Add the FirebaseAppDelegateProxyEnabled flag in the app’s Info.plist file and set it to NO(boolean value)


Sending Messages

In order to send messages, you need to create a Delivery using the deliver() method. This method requires a Private Key, and thus only available in the Backend SDKs.

Passing Variables

You can specify variables in different parts of your message using {{variable_name}} placeholders, and pass along the actual values in the data parameter when calling deliver(). This will replace the placeholders in the template with the actual values from data prior to sending out the message.

Most fields support variables, such as the subject of an Email, the body of an SMS, and so on.

Template vs Ad-Hoc

To use a pre-saved Template, you will need to pass the template type (email / push / sms / whatsapp / universal) and the template identifier (example: forgot-password) in the following format: <type>/<identifier>.

To send an ad-hoc Message, you will need to pass the template type (email / push / sms / whatsapp / universal) as well as a content parameter that contains all the attributes of that specific template type.

Backend

// Sending a Message Template
dashx.deliver('email/forgot-password', {
to: user.email,
data: { reset_password_token: '<TOKEN>' }
});

// Sending an Ad-Hoc Message
dashx.deliver('email', {
content: {
name: 'Contact us',
from: 'noreply@dashxdemo.com',
to: [email, 'sales@dashx.com'],
subject: 'Contact Us Form',
html_body: `
<mjml>
<mj-body>
<mj-section>
<mj-column>
<mj-divider border-color="#F45E43"></mj-divider>
<mj-text>Thanks for reaching out! We will get back to you soon!</mj-text>
<mj-text>Your feedback: </mj-text>
<mj-text>Name: {{name}}</mj-text>
<mj-text>Email: {{email}}</mj-text>
<mj-text>Feedback: {{feedback}}</mj-text>
<mj-divider border-color="#F45E43"></mj-divider>
</mj-column>
</mj-section>
</mj-body>
</mjml>`
},
data: {
name,
email,
feedback
}
});

Subscribing your Device

To receive Push Notifications on Web, iOS and Android, you first need to subscribe (ie. register your device token with DashX).

Simply use the subscribe() method to save the current device as one of the contacts that belongs to the current identity.

note

Read more about setting identity in the User Management guide.

To verify if the current device has been saved,

  • Head to the User Management app
  • Open either Users or Visitors
  • Filter & locate the identity you are looking for, and click on their name to open up the Details side pane.
  • Under the Related section, select Contacts as shown in the screenshot.
Contacts

Frontend (Browser)

import dx from 'lib/dashx'

dx.subscribe();

Frontend (Mobile)

DashX.subscribe();

Unsubscribing your Device

To stop receiving Push Notifications, simply use the unsubscribe() method to unregister the current device token. This is useful when you have a Notification Preferences screen on your web or mobile app that allows the user to manually unsubscribe from Push Notifications.

note

If you have implemented the User Logout flow in the User Management guide, you can just call reset() which implicitly calls unsubscribe(). This ensures that you do NOT continue sending push notifications to a device once the user has logged out, or is logged into another account in the same device.

If your user is offline, note that the device token will be unregistered, but the contact status may not reflect correctly on DashX.

Frontend (Browser)

import dx from 'lib/dashx'

dx.unsubscribe();

Frontend (Mobile)

DashX.unsubscribe();

Managing Preferences

Preference Data

DashX returns the Stored Preferences of a User in the following format:

{
"my-preference-1": {
"enabled": true,
"email": true,
"push": false,
"sms": false,
"whatsapp": false
},
"my-preference-2": {
"enabled": false,
"email": true,
"push": true,
"sms": true,
"whatsapp": true
}
}

Here is the same data represented as a table:

IdentifierEnabledEmailPushSMSWhatsApp
my-preference-1
my-preference-2

For a User to receive a template gated by a specific preference, their stored preference must have enabled set to true, and the individual channel settings to be true. If enabled is set to false, then the individual channel settings are disregarded.

Frontend (Browser)

import dx from 'lib/dashx'

const preferenceData = await dx.fetchStoredPreferences();

// ... modify preferenceData ...

dx.saveStoredPreferences(preferenceData);

Frontend (Mobile)

DashX.fetchStoredPreferences { response in
// ...
} failureCallback: { error in
// ...
}
DashX.saveStoredPreferences(preferenceData: dictionary) { response in
// ...
} failureCallback: { error in
// ...
}

Frontend (Mobile)

// In SceneDelegate, add the following functions

func scene(_ scene: UIScene, willConnectTo session: UISceneSession, options connectionOptions: UIScene.ConnectionOptions) {
// ...
DashX.handleUserActivity(userActivity: connectionOptions.userActivities.first)
// ...
}

func scene(_ scene: UIScene, continue userActivity: NSUserActivity) {
// ...
DashX.handleUserActivity(userActivity: userActivity)
// ...
}
// This method is called in your AppDelegate when you receive a Universal Link
override func handleLink(url: URL) {
// Perform actions like navigating to a specific view
}