iOS 구현

다음 예는 iOS 클라이언트에서 인스턴스 ID를 구현하는 데 도움이 됩니다. 이 예에서는 Firebase 클라우드 메시징용 iOS 클라이언트의 토큰을 관리하는 데 사용하는 GCM 범위를 사용합니다.

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]를 호출하여 최신 토큰을 가져올 수 있습니다.

클라우드 메시징의 토큰 생성을 관찰하기 위해 사용할 수 있는 특정 대리자가 있습니다.