Mobile Push Onboarding
Engage Premier requires a Business tier account and includes Engage Foundations and Unify.
See the available plans, or contact Support.
This page walks you through the process of setting up mobile push notifications using Segment, Twilio, and Firebase/Apple Developer.
Prerequisites
Please reach out to your CSM or AE prior to trying out this feature. This guide assumes familiarity with Swift and Kotlin and is intended for a developer audience.
Overview
You’ll set up mobile push in four stages:
- Set up analytics for mobile push.
- Add the Engage SDK plugin.
- Configure iOS push notifications.
- Configure Android push notifications.
- Configure mobile push in Engage.
1. Set up analytics for mobile push
Before you can send mobile pushes, you’ll need to set up analytics. In this step, you’ll integrate Segment’s mobile SDK into your app.
Add the Segment base SDK
This section outlines the process for adding Segment’s base SDK to your app, including the Analytics Kotlin, Analytics-Swift, and React Native libraries.
Kotlin
You must initialize your Analytics instance in the Application class, otherwise you may experience issues with customization and delivery confirmation.
Follow these steps to integrate Analytics Kotlin:
- Create a source by navigating to Connections > Sources > Add Source.
- Search for Kotlin (Android), then click Add source.
- Add the Analytics dependency to your
build.gradle
file. - Initialize and configure the client according to your requirements.
- Add the following permissions to
AndroidManifest.xml
:
<uses-permission android:name="android.permission.INTERNET"/>
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"/>
For detailed instructions on integrating Analytics Kotlin, follow the steps in the Analytics Kotlin getting started section.
Swift
Follow these steps to integrate Analytics-Swift for iOS & Apple:
- Create a source by navigating to Connections > Sources > Add Source.
- Search for Apple, then click Add source.
- Add the Analytics dependency to your application using either Swift package manager or Xcode.
- Initialize and configure the Analytics-Swift client.
For detailed instructions on integrating Analytics-Swift, follow the steps in the Analytics-Swift getting started section.
React Native
Follow these steps to integrate the React Native library:
- Create a source by navigating to Connections > Sources > Add Source.
- Search for React Native, then click Add source.
- Use yarn or npm to install
@segment/analytics-react-native
,@segment/sovran-react-native
, andreact-native-get-random-values
. - Initialize and configure the Analytics React Native client.
For detailed instructions on integrating Analytics for React Native, follow the steps in the Analytics for React Native getting started section.
2. Add the Engage SDK plugin
Next, you’ll add the Engage SDK plugins for both iOS and Android to your application.
Instructions for iOS
Now that you’ve integrated Analytics-Swift, follow the steps in this section to add the Engage Plugin for iOS.
2a. Add the Engage SDK plugin dependency
You can add the Engage SDK plugin using either Xcode or Package.swift
.
Instructions for adding the plugin with Xcode
- In the Xcode
File
menu, click Add Packages. -
In the Swift packages search dialog, enter the following URL:
https://github.com/segment-integrations/analytics-swift-engage
- You’ll then have the option to pin to a version or a specific branch, as well as to the project in your workspace. Once you’ve made your selections, click
Add Package
.
Instructions for adding the plugin with Package.swift
- Open the
Package.swift
file and add the following to thedependencies
section:
.package(
name: "Segment",
url: "https://github.com/segment-integrations/analytics-swift-engage.git",
from: "1.1.2"
),
2b. Import the plugin
-
Import the plugin in the file where you configure your Analytics instance:
import Segment import TwilioEngage // <-- Add this line.
-
After your Analytics-Swift library setup, call
analytics.add(plugin: ...)
to add an instance of the plugin to the Analytics timeline:let analytics = Analytics(configuration: Configuration(writeKey: "<YOUR WRITE KEY>") .flushAt(3) .trackApplicationLifecycleEvents(true)) let engage = TwilioEngage { previous, current in print("Push Status Changed /(current)") } analytics.add(plugin: engage)
-
To start receiving and handling mobile push notifications, add or modify the following methods in your
AppDelegate
:
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {
//Add the following:
let center = UNUserNotificationCenter.current()
center.delegate = self
center.requestAuthorization(options: [.sound, .alert, .badge]) { (granted, error) in
guard granted else {
Analytics.main.declinedRemoteNotifications()
Tab1ViewController.addPush(s: "User Declined Notifications")
return
}
DispatchQueue.main.async {
UIApplication.shared.registerForRemoteNotifications()
}
}
// The following conditional statement is necessary to handle remote notifications in older versions of iOS.
if let notification = launchOptions?[UIApplication.LaunchOptionsKey.remoteNotification] as? [String: Codable] {
Tab1ViewController.addPush(s: "App Launched via Notification \(notification)")
Analytics.main.receivedRemoteNotification(userInfo: notification)
}
...
return true
}
func application(_ application: UIApplication, didRegisterForRemoteNotificationsWithDeviceToken deviceToken: Data) {
// Segment event to register for remote notifications
Analytics.main.registeredForRemoteNotifications(deviceToken: deviceToken)
}
func application(_ application: UIApplication, didFailToRegisterForRemoteNotificationsWithError error: Error) {
// Segment event for failure to register for remote notifications
Analytics.main.failedToRegisterForRemoteNotification(error: error)
}
func application(_ application: UIApplication, didReceiveRemoteNotification userInfo: [AnyHashable : Any]) async -> UIBackgroundFetchResult {
// Segment event for receiving a remote notification
Analytics.main.receivedRemoteNotification(userInfo: userInfo)
// TODO: Customize notification handling based on the received userInfo.
// Implement actions or UI updates based on the notification content.
return .noData
}
func userNotificationCenter(_ center: UNUserNotificationCenter, didReceive response: UNNotificationResponse) async {
let userInfo = response.notification.request.content.userInfo
//Segment event for receiving a remote notification
Analytics.main.receivedRemoteNotification(userInfo: userInfo)
// TODO: Customize notification response handling based on the received userInfo.
// Implement actions based on the user's response to the notification.
// Example: Navigate to a specific screen or perform an action based on the notification.
}
The previous steps are required. For configuration options, including subscription statuses and media handling, visit the getting started section of Segment’s Twilio Engage Plugin documentation on GitHub.
Instructions for Android
Now that you’ve integrated Analytics for Kotlin, follow these steps to add the Engage Plugin for Android:
-
Add the following to your Gradle dependencies:
implementation 'com.segment.analytics.kotlin.destinations:engage:<LATEST_VERSION>'
-
Add the following service to the
application
tag of yourAndroidManifest.xml
file:<service android:name="com.segment.analytics.kotlin.destinations.engage.EngageFirebaseMessagingService" android:exported="true"> <intent-filter> <action android:name="com.google.firebase.INSTANCE_ID_EVENT"/> <action android:name="com.google.firebase.MESSAGING_EVENT" /> </intent-filter> </service>
-
Add this plugin to your Analytics instance:
analytics.add(TwilioEngage(applicationContext))
The previous steps are required. For configuration options, including subscription statuses and customized actions, visit the getting started section of Segment’s Twilio Engage Destination documentation on GitHub.
Next, you’ll configure your iOS and Android push credentials for use with Twilio Notify and Twilio Notifications.
3. Configure iOS push notifications
3a. Set up an App ID
Before you begin, log into your Apple development account and click on Identifiers under the Certificates, Identifiers & Profiles section. This will show a list of identifiers, including App IDs.
Option 1: Use an existing App ID
- If your App ID is already on this list, click on it; a list of capabilities will pop up.
- Check the Push Notifications option.
- Ignore the Configure button for now. Click Save.
Option 2: Create a new App ID
- If your App ID isn’t on this list, click the + symbol to add a new App ID.
- Choose App IDs and click the Continue button.
- Give your app a description.
- Enter an Explicit Bundle ID that matches the bundle identifier (such as
com.twilio.notify.NotifyQuickstart
) of your app in Xcode. - Under Capabilities, check Push Notifications.
- Click Continue.
- Click Register to confirm and create your new App ID.
3b. Create a certificate
Next, you’ll create a push notification certificate, which lets your app receive notifications. You can either make a development certificate or a production certificate. This guide explains how to make a development certificate. Segment recommends that you use Xcode managed certificates.
Option 1: Use an Xcode managed certificate
- In your Xcode project, go to the General pane of the target for your iOS application.
- In the Signing section, check Automatically manage signing.
- If you are using the Quickstart app and see a provisioning error message, you may need to rename the bundle ID to a unique identifier. To do so, give your bundle a new name, then enter your new identifier in the Identity section of the General pane.
- Go to the Capabilities tab and make sure that Push Notifications are enabled.
- Verify that you successfully created your certificates:
- Sign in to the Apple developer portal and click on Certificates, IDs & Profile. In the Certificates section, select Development or Production, depending on the type of certificate you want to verify.
- Alternatively, go to Applications > Utilities > Keychain Access and select Certificates. Search for
iPhone
, and verify that your certificate has a disclosure triangle, which indicates that your private key exists in the keychain.
Option 2: Manually create a certificate
Segment recommends that you use Xcode managed certificates for your application. If you prefer to create your certificate manually, follow these steps:
- Add a certificate on the Apple Developer Portal.
- Under Services, select Apple Push Notification service SSL (Sandbox & Production), then click Continue.
- In the text box, select the App ID you previously created, then click Continue.
- You’re prompted to create a Certificate Signing Request (CSR) and given instructions on how to do it. Create one.
- Once you’ve created a CSR, click Continue.
- Upload the CSR, then click Generate to generate your certificate.
You just created an Apple Development iOS Push Services certificate, which you can now download and double-click to add to your Mac’s keychain.
3c. Create a credential for Twilio
- On your Mac, go to Applications > Utilities > Keychain Access, then select My Certificates.
- Right-click your new certificate. It should be labeled Apple Development iOS Push Services.
- Choose Export.
- Save your credential file as
cred.p12
; leave the password blank.
You’ll extract your certificate key and private key from this file — you need these two keys to create a Twilio credential. First, run this command in Terminal:
openssl pkcs12 -in cred.p12 -nokeys -out cert.pem -nodes
cert.pem
is your certificate key file. Next, run the following command in the terminal:
openssl pkcs12 -in cred.p12 -nocerts -out key.pem -nodes
key.pem
is your private key file. Next, run this command to process this key:
openssl rsa -in key.pem -out key.pem
You can now paste your credentials into the modal found in the Twilio Console. Make sure that you strip anything outside of the -----BEGIN CERTIFICATE-----
and -----END CERTIFICATE-----
boundaries and outside of the -----BEGIN RSA PRIVATE KEY-----
and -----END RSA PRIVATE KEY-----
boundaries before pasting your credentials. Check the Sandbox button if you made a development certificate. Sandbox is synonymous with development mode.
Once you save a credential, the CERTIFICATE
and PRIVATE KEY
fields are hidden for security reasons.
After you’ve pasted your credentials, click Save. You should see an SID appear on the new page; copy it to your clipboard, as you’ll need it in the next step.
3d. Configure your Twilio Service to use your APNS credentials
Twilio lets you build multiple applications within a single account. To separate those applications, you need to create Service instances that hold all the data and configuration for a given application.
To do so, you’ll need to configure your Service instance to use the Credential that contains your APNS certificate and private key. You can do that using the Services page in the Console. You’ll need to update your Service with the Twilio Push Credential SID.
If you’re just getting started, set up the APN credential first, then create your Service by clicking the blue plus button on the Services Console page.
4. Configure Android push notifications
Follow the steps in Twilio’s Configuring Android Push Notifications.
During Step 5, Upload your API Key to Twilio, follow these steps:
- In the Firebase console, click the Cloud Messaging tab.
- Select the three dots menu next to Cloud Messaging API (Legacy) Disabled, then select Manage API in Google Cloud Console. A new window opens.
- In the new Cloud Messaging window, select Enable.
- Return to the Firebase Cloud Messaging tab and refresh the page.
- Cloud Messaging API (Legacy) is now enabled. Copy the server key; you’ll need it later.
With your server key copied, finish steps 5 and 6 in the Twilio documentation.
5. Configure mobile push in Engage
Follow these steps to set up mobile push in Twilio Engage.
5a. Set up Twilio credentials
Follow the steps in 5a only if you’re new to Twilio Engage Premier. If you’ve already configured messaging services as part of Twilio Engage Premier onboarding, you can skip to 5b.
- In your Twilio console, select the Account dropdown menu, then API keys & tokens.
- On the Auth tokens & API keys page, click Create API key.
- Enter a name for the API key in the Friendly name field.
- Set the region to United States (US1) - Default and key type to Main.
- Click Create API Key.
- Copy and save both the SID and Secret field contents.
- Return to the API keys & tokens page. In the Live credentials section, copy the Account SID credentials.
- Return to your Segment workspace and navigate to Engage > Engage settings > Channels. Under SMS Service with Twilio, click the Get Started button. The Set up and validate your Twilio account page appears.
- Under Enter your Twilio API Key information, paste the Account SID, API Key SID, and API Key Secret you copied above into their corresponding fields.
- Click Verify, then select the messaging services you want to use in your space.
- Click Save Twilio Account.
Removing messaging services
To remove a messaging service, navigate to Engage > Engage settings > Channels and click the pencil icon under Twilio messaging service. Enter the account credentials by either using the API key secret or creating a new API key. Once you’ve selected the desired services, they will override the existing ones, effectively removing the ones you no longer need.
5b. Create a new push service
Complete mobile push onboarding by creating a new push service:
- In your Segment workspace, navigate to Engage > Engage settings.
- Click the pencil icon next to Messaging services, then click Create new push service.
- If you don’t see the pencil icon, select Create new push service.
- Name the push service, select or create APN and FCM credentials, then click Create Push Service.
- Your new messaging service appears in the Add messaging services dropdown. Select it, then click Save.
Build a mobile push template
Now that you’ve completed mobile push setup, you’re ready to build a mobile push template.
This page was last modified: 23 Jan 2024
Need support?
Questions? Problems? Need more info? Contact Segment Support for assistance!