iOS Implementation

The following examples will help you implement Instance ID in an iOS client. Note that these examples use the GCM scope, which you would use to manage tokens for an iOS client for Firebase Cloud Messaging.

Set up your CocoaPods dependencies

Instance ID uses CocoaPods to install and manage dependencies. Open a terminal window and navigate to the location of the Xcode project for your application. If you have not already created a Podfile for your application, create one now:

pod init

Open the Podfile created for your application and add the following:

pod 'FirebaseInstanceId'

Save the file and run:

pod install

This creates an .xcworkspace file for your application. Use this file for all future development on your application.

Generate a token

Generating tokens requires a Project ID generated by the Google Developers Console.

NSString *authorizedEntity = PROJECT_ID;
String *scope = kFIRInstanceIDScopeFirebaseMessaging;
NSDictionary *options = @{
  @"apns_token" : <APNS Token data>,
  // 1 if APNS sandbox token else 0
  @"apns_sandbox" : @(1),
[[FIRInstanceID instanceID] tokenWithAuthorizedEntity:authorizedEntity
                  ^(NSString * _Nullable token, NSError * _Nullable error) {
                      // ...

Manage tokens and Instance IDs

Instance ID lets you delete and refresh tokens.

Delete tokens and Instance IDs

NSString *authorizedEntity = PROJECT_ID; // Project ID
String *scope = kFIRInstanceIDScopeFirebaseMessaging;
FIRInstanceIDDeleteTokenHandler handler = ^void(NSError *error) {
  if (error) {
    // Failed to delete the token. Check error and do an exponential
    // backoff to retry again.
  } else {
    // Successfully deleted the token.
[[FIRInstanceID instanceID]

You can also delete the Instance ID itself, in which case next time you call getInstance() you will get a new Instance ID:

[FIRInstanceID instanceID] deleteIDWithHandler:^(NSError *error) {
      if error != nil {
        NSLog(@"Error deleting instance ID: %@", error);

Refresh tokens

The Instance ID service may create or regenerate tokens. When this occurs, a notification will be sent. You can listen to this notification by adding an observer for notifications named kFIRInstanceIDTokenRefreshNotification.

[[NSNotificationCenter defaultCenter] addObserver:self
         name:kFIRInstanceIDTokenRefreshNotification object:nil];

This observer must be created before the token is created, for example prior to calling [FIRApp configure]. The latest token can be retrieved by calling [[FIRInstanceID instanceID] token].

Note that for observing generation of tokens for Cloud Messaging, there is a specific delegate available.

Send feedback about...

Instance ID