下列範例可協助您在 iOS 用戶端中導入執行個體 ID。 請注意,這些範例使用 GCM 範圍,您會使用這個範圍管理 iOS 用戶端的權杖,以進行 Firebase 雲端通訊。
設定 CocoaPods 依附元件
Instance 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);
}
}];
更新權杖
Instance ID 服務可能會建立或重新產生權杖。發生這種情況時,系統會傳送通知。您可以為名為 kFIRInstanceIDTokenRefreshNotification
的通知新增觀察器,即可聆聽這則通知。
[[NSNotificationCenter defaultCenter] addObserver:self
selector:@selector(tokenRefreshNotification:)
name:kFIRInstanceIDTokenRefreshNotification object:nil];
這個觀察器必須在建立權杖前建立,例如在呼叫 [FIRApp configure]
前。您可以呼叫 [[FIRInstanceID instanceID] token]
擷取最新權杖。
請注意,如要觀察 Cloud Messaging 的權杖產生作業,可以使用特定委派。