iOS 導入

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

設定 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] 可擷取最新的權杖。

請注意,為了觀察雲端通訊的產生權杖,你可以使用特定的委派項目。