Ready to send your first notification? Of course, you're not! That's why you're here. But don't worry, we'll get you registered so you can start sending notifications faster than a collision-free hash table lookup (OK, maybe not that fast).
A Notifications application involves two components:
The aim of this guide is to show you how these two components work together when you register for notifications. Let's get to it!
Before working with Twilio Notifications, we'll need to register our device with APNS. This registration will happen every app launch, and in our AppDelegate and we can specify the type of notification (sound, alert, or badge) that we'd like to accept. On the first launch, iOS will prompt us to enable push notifications with a popup alert.
1- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {2// Override point for customization after application launch.3if ([[[UIDevice currentDevice] systemVersion] floatValue] >= 8.0) {4[[UIApplication sharedApplication] registerUserNotificationSettings:[UIUserNotificationSettings5settingsForTypes:(UIUserNotificationTypeSound |6UIUserNotificationTypeAlert |7UIUserNotificationTypeBadge)8categories:nil]];910[UIApplication sharedApplication] registerForRemoteNotifications];11} else {12[[UIApplication sharedApplication] registerForRemoteNotifications];13}14return YES;15}
Once we've enabled notifications, iOS will send an asynchronous response to the app via the didRegisterForRemoteNotifications function. Make sure you've properly configured your iOS app for notifications or else the registration won't work.
Once we've received a successful registration response from the didRegisterForRemote NotificationsWithDeviceToken method, it's time to create a Binding. A "Binding" represents a unique device that can receive a notification. It associates a unique device token (provided by iOS) with an identity and an optional set of tags that you define for your application. When you want to send a notification, Twilio will send your notification only to Bindings that match the parameters you specify (more on that later).
In iOS 13, the format of the string returned when you call the description
method on an NSData
object has changed from previous iOS versions. This means that code that parses the device token string from a call like [deviceToken description]
or similar, where deviceToken
is an NSData
object, will break in iOS 13.
The preferred way of creating a string of hex characters from bytes would be to iterate through each of the bytes and create a new string using a format string. There is an example in the Objective-C snippet for Creating a Binding.
The client app should send a request to the server containing the device token and any additional information the server might need to create the binding (typically Identity and BindingType). We'll use the NSURLSession networking API that is part of the iOS standard library to make the request. You could also use another library, such as AFNetworking or Alamofire.
The last step on the client side is storing the Endpoint identifier generated by Twilio and included in the response. Storing the Endpoint and reusing it in subsequent requests will allow us to avoid creating duplicated Bindings when the device token changes. Here we use the KeychainAccess helper class from our quickstart app but you can use your own way of accessing the keychain.
1- (NSString*) createDeviceTokenString:(NSData*) deviceToken {2const unsigned char *tokenChars = deviceToken.bytes;34NSMutableString *tokenString = [NSMutableString string];5for (int i=0; i < deviceToken.length; i++) {6NSString *hex = [NSString stringWithFormat:@"%02x", tokenChars[i]];7[tokenString appendString:hex];8}9return tokenString;10}1112-(void) registerDevice:(NSData *) deviceToken identity:(NSString *) identity {13// Create a POST request to the /register endpoint with device variables to register for Twilio Notifications1415NSString *deviceTokenString = [self createDeviceTokenString:deviceToken];161718NSURLSession *session = [NSURLSession sharedSession];1920NSURL *url = [NSURL URLWithString:serverURL];21NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url cachePolicy:NSURLRequestUseProtocolCachePolicy timeoutInterval:30.0];22request.HTTPMethod = @"POST";2324[request addValue:@"application/json" forHTTPHeaderField:@"Accept"];25[request addValue:@"application/json" forHTTPHeaderField:@"Content-Type"];2627NSDictionary *params = @{@"identity": identity,28@"BindingType": @"apn",29@"Address": deviceTokenString};3031NSError* err=nil32NSString *endpoint = [KeychainAccess readEndpoint:identity error:err];33if (err == nil){34[params setObject:endpoint forKey:@"endpoint"];35}3637NSError *error;38NSData *jsonData = [NSJSONSerialization dataWithJSONObject:params options:0 error:&error];39request.HTTPBody = jsonData;4041NSURLSessionDataTask *task = [session dataTaskWithRequest:request completionHandler:^(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error) {4243NSString *responseString = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];44NSLog(@"Response: %@", responseString);4546if (error == nil) {47NSDictionary *response = [NSJSONSerialization JSONObjectWithData:data options:0 error:nil];48NSLog(@"JSON: %@", response);4950[KeychainAccess saveEndpoint:identity endpoint:response["endpoint"]]5152} else {53NSLog(@"Error: %@", error);54}55}];56[task resume];57}
In our server app, we'll receive the POST
request. It'll contain the following
four parameters.
name | description |
---|---|
Identity | The Identity to which this Binding belongs. Identity is defined by your application and can have multiple endpoints. |
BindingType | The type of the Binding determining the transport technology to use. We will use apn here. |
Address | The device token obtained from iOS. |
Endpoint | The identifier of the device to which this registration belongs. This is generated the first time you create a Binding. Then you need to store it in the keychain and provide it in your subsequent registrations to avoid duplicating Bindings even if the device token changes. |
Notify uses Identity as a unique identifier of a user. You should not use directly identifying information (aka personally identifiable information or PII) like a person's name, home address, email or phone number, etc., as Identity because the systems that will process this attribute assume it is not directly identifying information.
We'll use index.js in our server app and these four parameters to send an API call to Twilio, using the next generation Twilio Node Helper Library. This will help us create a new Binding. We implement this logic in the /register endpoint, but this is not required. You can come up with your own API, and perhaps integrate it into a login or a session initialization flow.
1// Download the helper library from https://www.twilio.com/docs/node/install2const twilio = require("twilio"); // Or, for ESM: import twilio from "twilio";34// Find your Account SID and Auth Token at twilio.com/console5// and set the environment variables. See http://twil.io/secure6const accountSid = process.env.TWILIO_ACCOUNT_SID;7const authToken = process.env.TWILIO_AUTH_TOKEN;8const client = twilio(accountSid, authToken);910async function createBinding() {11const binding = await client.notify.v112.services("ISXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX")13.bindings.create({14address: "apn_device_token",15bindingType: "apn",16endpoint: "endpoint_id",17identity: "00000001",18tag: ["preferred device"],19});2021console.log(binding.sid);22}2324createBinding();
1{2"account_sid": "ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa",3"address": "apn_device_token",4"binding_type": "apn",5"credential_sid": null,6"date_created": "2015-07-30T20:00:00Z",7"date_updated": "2015-07-30T20:00:00Z",8"endpoint": "endpoint_id",9"identity": "00000001",10"notification_protocol_version": "3",11"service_sid": "ISXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX",12"sid": "BSaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa",13"tags": [14"26607274"15],16"links": {17"user": "https://notify.twilio.com/v1/Services/ISaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Users/24987039"18},19"url": "https://notify.twilio.com/v1/Services/ISaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Bindings/BSaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa"20}
Now that we've registered the client app with APNS and created a Binding, it's time to send some notifications! Check out our Sending Notifications guide for more information.