iOS 導入

下列範例可協助您在 iOS 用戶端中導入執行個體 ID。請注意,這些範例使用的是 GCM 範圍,用來管理 Firebase 雲端通訊 iOS 用戶端的權杖。

設定 CocoaPods 依附元件

執行個體 ID 會使用 CocoaPods 安裝及管理依附元件。開啟終端機視窗,然後前往應用程式的 Xcode 專案位置。如果您尚未為應用程式建立 Podfile,請立即建立一個:

pod init

請開啟為您的應用程式建立的 Podfile,並新增下列指令:

pod 'FirebaseInstanceId'

儲存檔案並執行:

pod install

這個步驟會為您的應用程式建立 .xcworkspace 檔案。應用程式日後的所有開發作業都將使用這個檔案。

產生權杖

產生權杖需要由 Google Developers Console 產生的專案 ID。

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
                                                scope:scope
                                              options:options
                                              handler:
                  ^(NSString * _Nullable token, NSError * _Nullable error) {
                      // ...
}];

管理權杖和執行個體 ID

執行個體 ID 可讓您刪除及更新權杖。

刪除權杖和執行個體 ID

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]
    deleteTokenWithAuthorizedEntity:authorizedEntity
                              scope:scope
                            handler:handler];

您也可以刪除執行個體 ID 本身,在此情況下,當您下次呼叫 getInstance() 時,將取得新的執行個體 ID:

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

重新整理權杖

執行個體 ID 服務可能會建立或重新產生權杖。發生這種情況時,系統會傳送通知。如要監聽這則通知,您可以新增名為 kFIRInstanceIDTokenRefreshNotification 的通知觀測器。

[[NSNotificationCenter defaultCenter] addObserver:self
         selector:@selector(tokenRefreshNotification:) 
         name:kFIRInstanceIDTokenRefreshNotification object:nil];

這個觀察器必須在權杖建立前建立,例如呼叫 [FIRApp configure] 之前。呼叫 [[FIRInstanceID instanceID] token] 即可擷取最新的權杖。

請注意,用於觀察雲端通訊的產生權杖時,有可用的特定委派