Skip to contentSkip to navigationSkip to topbar
On this page

Registering for Notifications on iOS


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:

  • A client (iOS) app that registers for and receives notifications
  • A server app that creates bindings and sends notifications

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!


Table of Contents

table-of-contents page anchor

Client: Registering a Device with APNS

client-registering-a-device-with-apns page anchor

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.

Register a DeviceLink to code sample: Register a Device
1
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
2
// Override point for customization after application launch.
3
if ([[[UIDevice currentDevice] systemVersion] floatValue] >= 8.0) {
4
[[UIApplication sharedApplication] registerUserNotificationSettings:[UIUserNotificationSettings
5
settingsForTypes:(UIUserNotificationTypeSound |
6
UIUserNotificationTypeAlert |
7
UIUserNotificationTypeBadge)
8
categories:nil]];
9
10
[UIApplication sharedApplication] registerForRemoteNotifications];
11
} else {
12
[[UIApplication sharedApplication] registerForRemoteNotifications];
13
}
14
return 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.


Client + Server: Creating a Binding

client--server-creating-a-binding page anchor

Client

client page anchor

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).

(warning)

Warning

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(link takes you to an external page) or Alamofire(link takes you to an external page).

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 {
2
const unsigned char *tokenChars = deviceToken.bytes;
3
4
NSMutableString *tokenString = [NSMutableString string];
5
for (int i=0; i < deviceToken.length; i++) {
6
NSString *hex = [NSString stringWithFormat:@"%02x", tokenChars[i]];
7
[tokenString appendString:hex];
8
}
9
return tokenString;
10
}
11
12
-(void) registerDevice:(NSData *) deviceToken identity:(NSString *) identity {
13
// Create a POST request to the /register endpoint with device variables to register for Twilio Notifications
14
15
NSString *deviceTokenString = [self createDeviceTokenString:deviceToken];
16
17
18
NSURLSession *session = [NSURLSession sharedSession];
19
20
NSURL *url = [NSURL URLWithString:serverURL];
21
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url cachePolicy:NSURLRequestUseProtocolCachePolicy timeoutInterval:30.0];
22
request.HTTPMethod = @"POST";
23
24
[request addValue:@"application/json" forHTTPHeaderField:@"Accept"];
25
[request addValue:@"application/json" forHTTPHeaderField:@"Content-Type"];
26
27
NSDictionary *params = @{@"identity": identity,
28
@"BindingType": @"apn",
29
@"Address": deviceTokenString};
30
31
NSError* err=nil
32
NSString *endpoint = [KeychainAccess readEndpoint:identity error:err];
33
if (err == nil){
34
[params setObject:endpoint forKey:@"endpoint"];
35
}
36
37
NSError *error;
38
NSData *jsonData = [NSJSONSerialization dataWithJSONObject:params options:0 error:&error];
39
request.HTTPBody = jsonData;
40
41
NSURLSessionDataTask *task = [session dataTaskWithRequest:request completionHandler:^(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error) {
42
43
NSString *responseString = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
44
NSLog(@"Response: %@", responseString);
45
46
if (error == nil) {
47
NSDictionary *response = [NSJSONSerialization JSONObjectWithData:data options:0 error:nil];
48
NSLog(@"JSON: %@", response);
49
50
[KeychainAccess saveEndpoint:identity endpoint:response["endpoint"]]
51
52
} else {
53
NSLog(@"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.

namedescription
IdentityThe Identity to which this Binding belongs. Identity is defined by your application and can have multiple endpoints.
BindingTypeThe type of the Binding determining the transport technology to use. We will use apn here.
AddressThe device token obtained from iOS.
EndpointThe 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.
(warning)

Do not use Personally Identifiable Information for Identity

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(link takes you to an external page). 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/install
2
const twilio = require("twilio"); // Or, for ESM: import twilio from "twilio";
3
4
// Find your Account SID and Auth Token at twilio.com/console
5
// and set the environment variables. See http://twil.io/secure
6
const accountSid = process.env.TWILIO_ACCOUNT_SID;
7
const authToken = process.env.TWILIO_AUTH_TOKEN;
8
const client = twilio(accountSid, authToken);
9
10
async function createBinding() {
11
const binding = await client.notify.v1
12
.services("ISXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX")
13
.bindings.create({
14
address: "apn_device_token",
15
bindingType: "apn",
16
endpoint: "endpoint_id",
17
identity: "00000001",
18
tag: ["preferred device"],
19
});
20
21
console.log(binding.sid);
22
}
23
24
createBinding();

Output

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.

Next: Sending Notifications »

Need some help?

Terms of service

Copyright © 2024 Twilio Inc.