Your iOS app users can receive push notifications from Twilio Conversations when important events occur, such as a new message in the conversation.
You will need to do some configuration and integration to get push notifications working with your app, and this guide will walk you through the necessary steps:
IMPORTANT: The default enabled flag for new Service instances for all Push Notifications is false
. This means that Push will be disabled until you explicitly enable it. To do so, please follow our Push Notification Configuration Guide.
Note: You will need to configure the sound
setting value for each push notification type you want the sound
payload parameter to present for, with required value. More information can be found in the previously mentioned Push Notification Configuration Guide.
Managing your push credentials will be necessary, as your device token is required for the Conversations SDK to be able to send any notifications through APNS. Let's go through the process of managing your push credentials.
Your iOS project's AppDelegate
class contains a series of application lifecycle methods. These methods include event listeners such as your app moving to the background or foreground.
When working with push notifications in your iOS application, it is quite likely you will find yourself needing to process push registrations or received events prior to the initialization of your Conversations client. For this reason, we recommend you create a spot to store any registrations or push messages your application receives prior to the client being fully initialized.
The best option for this is to store the registrations or push messages in an instance of a helper class. This way, your Conversations client can process these values post-initialization if necessary or real-time otherwise. If you are doing a quick proof of concept, you could even define these on the application delegate itself but we recommend you refrain from doing this as storing state on the application delegate is not considered a best practice on iOS.
We will assume that you have defined the following properties in a way that makes them accessible to your application delegate method and Conversations client initialization:
Your users can choose to authorize notifications or not - if they have authorized notifications, you can register the application for remote notifications from Twilio. Typically, you would do this in AppDelegate.swift
in the didFinishLaunchingWithOptions
function.
1// Add this to the didFinishLaunchingWithOptions function or a similar place2// once you get granted permissions3UNUserNotificationCenter *currentNotificationCenter = [UNUserNotificationCenter currentNotificationCenter];4[currentNotificationCenter getNotificationSettingsWithCompletionHandler:^(UNNotificationSettings *settings) {5if (settings.authorizationStatus == UNAuthorizationStatusAuthorized) {6[UIApplication.sharedApplication registerForRemoteNotifications];7}8}];
After successfully registering for remote notifications, the Apple Push Notification Service (APNS) will send back a unique device token that identifies this app installation on this device. The Twilio Conversations Client will take that device token (as a Data
object), and pass it to Twilio's servers to use to send push notifications to this device.
1- (void)application:(UIApplication*)application didRegisterForRemoteNotificationsWithDeviceToken:(NSData*)deviceToken {2if (self.conversationsClient && self.conversationsClient.user) {3[self.conversationsClient registerWithNotificationToken:deviceToken4completion:^(TCHResult *result) {5if (![result isSuccessful]) {6// try registration again or verify token7}8}];9} else {10self.updatedPushToken = deviceToken;11}12}1314- (void)application:(UIApplication*)application didFailToRegisterForRemoteNotificationsWithError:(NSError*)error {15NSLog(@"Failed to get token, error: %@", error);16self.updatedPushToken = nil;17}
We print an error if it fails, but if it succeeds, we either update the Conversations client directly or save the token for later use.
Make sure you have created an "Apple Push Notification service SSL (Sandbox & Production)" certificate on the Apple Developer Portal for your application first.
We're going to need to export both a certificate and a private key from Keychain Access:
openssl pkcs12 -in cred.p12 -nokeys -out cert.pem -nodes
openssl pkcs12 -in cred.p12 -nocerts -out key.pem -nodes
The resulting file should contain "-----BEGIN RSA PRIVATE KEY-----". If the file contains "-----BEGIN PRIVATE KEY-----" and run the following command:
openssl rsa -in key.pem -out key.pem
Strip anything outside of "-----BEGIN RSA PRIVATE KEY-----" and "-----END RSA PRIVATE KEY-----" boundaries and upload your credentials into the Twilio Platform through the Console.
To store your Credential, visit your Credentials Page and click on the Create New Credential
button.
The Credential SID for your new Credential is in the detail page labeled 'Credential SID.'
When you create your access token for the iOS clients, be sure to add your credential SID to the chat grant.
Each of the Twilio Helper Libraries makes provisions to add the push_credential_sid.
Please see the relevant documentation for your preferred Helper Library for details.
1var chatGrant = new ChatGrant({2serviceSid: ChatServiceSid,3pushCredentialSid: APNCredentialSid,4});
This is all of the integration you need on the server side to make push notifications work with Twilio Conversations. The next step is to set up your iOS application.
Let's go through the process for integrating push notifications into your iOS app.
The AppDelegate
class contains a series of application lifecycle methods. Many important events that occur like your app moving to the background or foreground have event listeners in this class. One of those is the applicationDidFinishLaunchingWithOptions
method.
In this method, we're going to want to integrate push notifications for our app
1UNUserNotificationCenter *currentNotificationCenter = [UNUserNotificationCenter currentNotificationCenter];2[currentCenter requestAuthorizationWithOptions:UNAuthorizationOptionBadge | UNAuthorizationOptionAlert | UNAuthorizationOptionSound3completionHandler:^(BOOL granted, NSError *error) {4// Add here your handling of granted or not granted permissions5}];6currentNotificationCenter.delegate = self;
The above code snippet asks the user's permission for notifications, and if granted, registers for remote (push) notifications. That's it! We're now registered for notifications.
Receiving notifications in our app lets us react to whatever event just occurred. It can trigger our app to update a view, change a status, or even send data to a server. Whenever the app receives a notification, the method didReceiveRemoteNotification
is fired
1// Do not forget to set up a delegate for UNUserNotificationCenter2- (void)userNotificationCenter:(UNUserNotificationCenter *)center3didReceiveNotificationResponse:(UNNotificationResponse *)response4withCompletionHandler:(void (^)(void))completionHandler {5NSDictionary *userInfo = response.notification.request.content.userInfo;6// If your application supports multiple types of push notifications,7// you may wish to limit which ones you send to the TwilioConversationsClient here8if (self.conversationsClient) {9// If your reference to the Conversations client exists and is initialized,10// send the notification to it11[self.conversationsClient handleNotification:userInfo completion:^(TCHResult *result) {12if (![result isSuccessful]) {13// Handling of notification was not successful, retry?14}15}];16} else {17// Store the notification for later handling18self.receivedNotification = userInfo;19}20}
We will pass the notification directly on to the Conversations client if it is initialized or store the event for later processing if not.
The userInfo parameter contains the data that the notification passes in from APNS. We can update our Conversations client by passing it into the singleton via the receivedNotification
method. The manager wraps the Conversations client methods that process the notifications appropriately.
Once your Conversations client is up and available, you can provide the push token your application received:
1if (self.updatedPushToken) {2[self.conversationsClient registerWithNotificationToken:self.updatedPushToken3completion:^(TCHResult *result) {4if (![result isSuccessful]) {5// try registration again or verify token6}7}];8}910if (self.receivedNotification) {11[self.conversationsClient handleNotification:self.receivedNotification12completion:^(TCHResult *result) {13if (![result isSuccessful]) {14// Handling of notification was not successful, retry?15}16}];17}
To update badge count on an application icon, you should pass badge count from the Conversations Client delegate to the application: