You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

1130 lines
43 KiB

5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
  1. /*
  2. * Copyright 2019 Google
  3. *
  4. * Licensed under the Apache License, Version 2.0 (the "License");
  5. * you may not use this file except in compliance with the License.
  6. * You may obtain a copy of the License at
  7. *
  8. * http://www.apache.org/licenses/LICENSE-2.0
  9. *
  10. * Unless required by applicable law or agreed to in writing, software
  11. * distributed under the License is distributed on an "AS IS" BASIS,
  12. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  13. * See the License for the specific language governing permissions and
  14. * limitations under the License.
  15. */
  16. #import "FIRInstanceID.h"
  17. #import <FirebaseInstallations/FIRInstallations.h>
  18. #import <FirebaseCore/FIRAppInternal.h>
  19. #import <FirebaseCore/FIRComponent.h>
  20. #import <FirebaseCore/FIRComponentContainer.h>
  21. #import <FirebaseCore/FIRLibrary.h>
  22. #import <FirebaseCore/FIROptions.h>
  23. #import <GoogleUtilities/GULAppEnvironmentUtil.h>
  24. #import <GoogleUtilities/GULUserDefaults.h>
  25. #import "FIRInstanceID+Private.h"
  26. #import "FIRInstanceIDAuthService.h"
  27. #import "FIRInstanceIDCheckinPreferences.h"
  28. #import "FIRInstanceIDCombinedHandler.h"
  29. #import "FIRInstanceIDConstants.h"
  30. #import "FIRInstanceIDDefines.h"
  31. #import "FIRInstanceIDLogger.h"
  32. #import "FIRInstanceIDStore.h"
  33. #import "FIRInstanceIDTokenInfo.h"
  34. #import "FIRInstanceIDTokenManager.h"
  35. #import "FIRInstanceIDUtilities.h"
  36. #import "FIRInstanceIDVersionUtilities.h"
  37. #import "NSError+FIRInstanceID.h"
  38. // Public constants
  39. NSString *const kFIRInstanceIDScopeFirebaseMessaging = @"fcm";
  40. #if defined(__IPHONE_10_0) && __IPHONE_OS_VERSION_MAX_ALLOWED >= __IPHONE_10_0
  41. const NSNotificationName kFIRInstanceIDTokenRefreshNotification =
  42. @"com.firebase.iid.notif.refresh-token";
  43. #else
  44. NSString *const kFIRInstanceIDTokenRefreshNotification = @"com.firebase.iid.notif.refresh-token";
  45. #endif // defined(__IPHONE_10_0) && __IPHONE_OS_VERSION_MAX_ALLOWED >= __IPHONE_10_0
  46. NSString *const kFIRInstanceIDInvalidNilHandlerError = @"Invalid nil handler.";
  47. // Private constants
  48. int64_t const kMaxRetryIntervalForDefaultTokenInSeconds = 20 * 60; // 20 minutes
  49. int64_t const kMinRetryIntervalForDefaultTokenInSeconds = 10; // 10 seconds
  50. // we retry only a max 5 times.
  51. // TODO(chliangGoogle): If we still fail we should listen for the network change notification
  52. // since GCM would have started Reachability. We only start retrying after we see a configuration
  53. // change.
  54. NSInteger const kMaxRetryCountForDefaultToken = 5;
  55. #if TARGET_OS_IOS || TARGET_OS_TV || TARGET_OS_WATCH
  56. static NSString *const kEntitlementsAPSEnvironmentKey = @"Entitlements.aps-environment";
  57. #else
  58. static NSString *const kEntitlementsAPSEnvironmentKey =
  59. @"Entitlements.com.apple.developer.aps-environment";
  60. #endif
  61. static NSString *const kAPSEnvironmentDevelopmentValue = @"development";
  62. /// FIRMessaging selector that returns the current FIRMessaging auto init
  63. /// enabled flag.
  64. static NSString *const kFIRInstanceIDFCMSelectorAutoInitEnabled =
  65. @"isAutoInitEnabledWithUserDefaults:";
  66. static NSString *const kFIRInstanceIDAPNSTokenType = @"APNSTokenType";
  67. static NSString *const kFIRIIDAppReadyToConfigureSDKNotification =
  68. @"FIRAppReadyToConfigureSDKNotification";
  69. static NSString *const kFIRIIDAppNameKey = @"FIRAppNameKey";
  70. static NSString *const kFIRIIDErrorDomain = @"com.firebase.instanceid";
  71. static NSString *const kFIRIIDServiceInstanceID = @"InstanceID";
  72. /**
  73. * The APNS token type for the app. If the token type is set to `UNKNOWN`
  74. * InstanceID will implicitly try to figure out what the actual token type
  75. * is from the provisioning profile.
  76. * This must match FIRMessagingAPNSTokenType in FIRMessaging.h
  77. */
  78. typedef NS_ENUM(NSInteger, FIRInstanceIDAPNSTokenType) {
  79. /// Unknown token type.
  80. FIRInstanceIDAPNSTokenTypeUnknown,
  81. /// Sandbox token type.
  82. FIRInstanceIDAPNSTokenTypeSandbox,
  83. /// Production token type.
  84. FIRInstanceIDAPNSTokenTypeProd,
  85. } NS_SWIFT_NAME(InstanceIDAPNSTokenType);
  86. @interface FIRInstanceIDResult ()
  87. @property(nonatomic, readwrite, copy) NSString *instanceID;
  88. @property(nonatomic, readwrite, copy) NSString *token;
  89. @end
  90. @interface FIRInstanceID ()
  91. // FIRApp configuration objects.
  92. @property(nonatomic, readwrite, copy) NSString *fcmSenderID;
  93. @property(nonatomic, readwrite, copy) NSString *firebaseAppID;
  94. // Raw APNS token data
  95. @property(nonatomic, readwrite, strong) NSData *apnsTokenData;
  96. @property(nonatomic, readwrite) FIRInstanceIDAPNSTokenType apnsTokenType;
  97. // String-based, internal representation of APNS token
  98. @property(nonatomic, readwrite, copy) NSString *APNSTupleString;
  99. // Token fetched from the server automatically for the default app.
  100. @property(nonatomic, readwrite, copy) NSString *defaultFCMToken;
  101. @property(nonatomic, readwrite, strong) FIRInstanceIDTokenManager *tokenManager;
  102. @property(nonatomic, readwrite, strong) FIRInstallations *installations;
  103. // backoff and retry for default token
  104. @property(nonatomic, readwrite, assign) NSInteger retryCountForDefaultToken;
  105. @property(atomic, strong, nullable)
  106. FIRInstanceIDCombinedHandler<NSString *> *defaultTokenFetchHandler;
  107. /// A cached value of FID. Should be used only for `-[FIRInstanceID appInstanceID:]`.
  108. @property(atomic, copy, nullable) NSString *firebaseInstallationsID;
  109. @end
  110. // InstanceID doesn't provide any functionality to other components,
  111. // so it provides a private, empty protocol that it conforms to and use it for registration.
  112. @protocol FIRInstanceIDInstanceProvider
  113. @end
  114. @interface FIRInstanceID () <FIRInstanceIDInstanceProvider, FIRLibrary>
  115. @end
  116. @implementation FIRInstanceIDResult
  117. - (id)copyWithZone:(NSZone *)zone {
  118. FIRInstanceIDResult *result = [[[self class] allocWithZone:zone] init];
  119. result.instanceID = self.instanceID;
  120. result.token = self.token;
  121. return result;
  122. }
  123. @end
  124. @implementation FIRInstanceID
  125. // File static to support InstanceID tests that call [FIRInstanceID instanceID] after
  126. // [FIRInstanceID instanceIDForTests].
  127. static FIRInstanceID *gInstanceID;
  128. + (instancetype)instanceID {
  129. // If the static instance was created, return it. This should only be set in tests and we should
  130. // eventually use proper dependency injection for a better test structure.
  131. if (gInstanceID != nil) {
  132. return gInstanceID;
  133. }
  134. FIRApp *defaultApp = [FIRApp defaultApp]; // Missing configure will be logged here.
  135. FIRInstanceID *instanceID =
  136. (FIRInstanceID *)FIR_COMPONENT(FIRInstanceIDInstanceProvider, defaultApp.container);
  137. return instanceID;
  138. }
  139. - (instancetype)initPrivately {
  140. self = [super init];
  141. if (self != nil) {
  142. // Use automatic detection of sandbox, unless otherwise set by developer
  143. _apnsTokenType = FIRInstanceIDAPNSTokenTypeUnknown;
  144. }
  145. return self;
  146. }
  147. + (FIRInstanceID *)instanceIDForTests {
  148. gInstanceID = [[FIRInstanceID alloc] initPrivately];
  149. [gInstanceID start];
  150. return gInstanceID;
  151. }
  152. - (void)dealloc {
  153. [[NSNotificationCenter defaultCenter] removeObserver:self];
  154. }
  155. #pragma mark - Tokens
  156. - (NSString *)token {
  157. if (!self.fcmSenderID.length) {
  158. return nil;
  159. }
  160. NSString *cachedToken = [self cachedTokenIfAvailable];
  161. if (cachedToken) {
  162. return cachedToken;
  163. } else {
  164. // If we've never had a cached default token, we should fetch one because unrelatedly,
  165. // this request will help us determine whether the locally-generated Instance ID keypair is not
  166. // unique, and therefore generate a new one.
  167. [self defaultTokenWithHandler:nil];
  168. return nil;
  169. }
  170. }
  171. - (void)instanceIDWithHandler:(FIRInstanceIDResultHandler)handler {
  172. FIRInstanceID_WEAKIFY(self);
  173. [self getIDWithHandler:^(NSString *identity, NSError *error) {
  174. FIRInstanceID_STRONGIFY(self);
  175. // This is in main queue already
  176. if (error) {
  177. if (handler) {
  178. handler(nil, error);
  179. }
  180. return;
  181. }
  182. FIRInstanceIDResult *result = [[FIRInstanceIDResult alloc] init];
  183. result.instanceID = identity;
  184. NSString *cachedToken = [self cachedTokenIfAvailable];
  185. if (cachedToken) {
  186. if (handler) {
  187. result.token = cachedToken;
  188. handler(result, nil);
  189. }
  190. // If no handler, simply return since client has generated iid and token.
  191. return;
  192. }
  193. [self defaultTokenWithHandler:^(NSString *_Nullable token, NSError *_Nullable error) {
  194. if (handler) {
  195. if (error) {
  196. handler(nil, error);
  197. return;
  198. }
  199. result.token = token;
  200. handler(result, nil);
  201. }
  202. }];
  203. }];
  204. }
  205. - (NSString *)cachedTokenIfAvailable {
  206. FIRInstanceIDTokenInfo *cachedTokenInfo =
  207. [self.tokenManager cachedTokenInfoWithAuthorizedEntity:self.fcmSenderID
  208. scope:kFIRInstanceIDDefaultTokenScope];
  209. return cachedTokenInfo.token;
  210. }
  211. - (void)setDefaultFCMToken:(NSString *)defaultFCMToken {
  212. if (_defaultFCMToken && defaultFCMToken && [defaultFCMToken isEqualToString:_defaultFCMToken]) {
  213. return;
  214. }
  215. _defaultFCMToken = defaultFCMToken;
  216. // Sending this notification out will ensure that FIRMessaging has the updated
  217. // default FCM token.
  218. NSNotification *internalDefaultTokenNotification =
  219. [NSNotification notificationWithName:kFIRInstanceIDDefaultGCMTokenNotification
  220. object:_defaultFCMToken];
  221. [[NSNotificationQueue defaultQueue] enqueueNotification:internalDefaultTokenNotification
  222. postingStyle:NSPostASAP];
  223. }
  224. - (void)tokenWithAuthorizedEntity:(NSString *)authorizedEntity
  225. scope:(NSString *)scope
  226. options:(NSDictionary *)options
  227. handler:(FIRInstanceIDTokenHandler)handler {
  228. if (!handler) {
  229. FIRInstanceIDLoggerError(kFIRInstanceIDMessageCodeInstanceID000,
  230. kFIRInstanceIDInvalidNilHandlerError);
  231. return;
  232. }
  233. // Add internal options
  234. NSMutableDictionary *tokenOptions = [NSMutableDictionary dictionary];
  235. if (options.count) {
  236. [tokenOptions addEntriesFromDictionary:options];
  237. }
  238. NSString *APNSKey = kFIRInstanceIDTokenOptionsAPNSKey;
  239. NSString *serverTypeKey = kFIRInstanceIDTokenOptionsAPNSIsSandboxKey;
  240. if (tokenOptions[APNSKey] != nil && tokenOptions[serverTypeKey] == nil) {
  241. // APNS key was given, but server type is missing. Supply the server type with automatic
  242. // checking. This can happen when the token is requested from FCM, which does not include a
  243. // server type during its request.
  244. tokenOptions[serverTypeKey] = @([self isSandboxApp]);
  245. }
  246. if (self.firebaseAppID) {
  247. tokenOptions[kFIRInstanceIDTokenOptionsFirebaseAppIDKey] = self.firebaseAppID;
  248. }
  249. // comparing enums to ints directly throws a warning
  250. FIRInstanceIDErrorCode noError = INT_MAX;
  251. FIRInstanceIDErrorCode errorCode = noError;
  252. if (FIRInstanceIDIsValidGCMScope(scope) && !tokenOptions[APNSKey]) {
  253. errorCode = kFIRInstanceIDErrorCodeMissingAPNSToken;
  254. } else if (FIRInstanceIDIsValidGCMScope(scope) &&
  255. ![tokenOptions[APNSKey] isKindOfClass:[NSData class]]) {
  256. errorCode = kFIRInstanceIDErrorCodeInvalidRequest;
  257. } else if (![authorizedEntity length]) {
  258. errorCode = kFIRInstanceIDErrorCodeInvalidAuthorizedEntity;
  259. } else if (![scope length]) {
  260. errorCode = kFIRInstanceIDErrorCodeInvalidScope;
  261. } else if (!self.installations) {
  262. errorCode = kFIRInstanceIDErrorCodeInvalidStart;
  263. }
  264. FIRInstanceIDTokenHandler newHandler = ^(NSString *token, NSError *error) {
  265. dispatch_async(dispatch_get_main_queue(), ^{
  266. handler(token, error);
  267. });
  268. };
  269. if (errorCode != noError) {
  270. newHandler(nil, [NSError errorWithFIRInstanceIDErrorCode:errorCode]);
  271. return;
  272. }
  273. FIRInstanceID_WEAKIFY(self);
  274. FIRInstanceIDAuthService *authService = self.tokenManager.authService;
  275. [authService fetchCheckinInfoWithHandler:^(FIRInstanceIDCheckinPreferences *preferences,
  276. NSError *error) {
  277. FIRInstanceID_STRONGIFY(self);
  278. if (error) {
  279. newHandler(nil, error);
  280. return;
  281. }
  282. FIRInstanceID_WEAKIFY(self);
  283. [self.installations installationIDWithCompletion:^(NSString *_Nullable identifier,
  284. NSError *_Nullable error) {
  285. FIRInstanceID_STRONGIFY(self);
  286. if (error) {
  287. NSError *newError =
  288. [NSError errorWithFIRInstanceIDErrorCode:kFIRInstanceIDErrorCodeInvalidKeyPair];
  289. newHandler(nil, newError);
  290. } else {
  291. FIRInstanceIDTokenInfo *cachedTokenInfo =
  292. [self.tokenManager cachedTokenInfoWithAuthorizedEntity:authorizedEntity scope:scope];
  293. if (cachedTokenInfo) {
  294. FIRInstanceIDAPNSInfo *optionsAPNSInfo =
  295. [[FIRInstanceIDAPNSInfo alloc] initWithTokenOptionsDictionary:tokenOptions];
  296. // Check if APNS Info is changed
  297. if ((!cachedTokenInfo.APNSInfo && !optionsAPNSInfo) ||
  298. [cachedTokenInfo.APNSInfo isEqualToAPNSInfo:optionsAPNSInfo]) {
  299. // check if token is fresh
  300. if ([cachedTokenInfo isFreshWithIID:identifier]) {
  301. newHandler(cachedTokenInfo.token, nil);
  302. return;
  303. }
  304. }
  305. }
  306. [self.tokenManager fetchNewTokenWithAuthorizedEntity:[authorizedEntity copy]
  307. scope:[scope copy]
  308. instanceID:identifier
  309. options:tokenOptions
  310. handler:newHandler];
  311. }
  312. }];
  313. }];
  314. }
  315. - (void)deleteTokenWithAuthorizedEntity:(NSString *)authorizedEntity
  316. scope:(NSString *)scope
  317. handler:(FIRInstanceIDDeleteTokenHandler)handler {
  318. if (!handler) {
  319. FIRInstanceIDLoggerError(kFIRInstanceIDMessageCodeInstanceID001,
  320. kFIRInstanceIDInvalidNilHandlerError);
  321. }
  322. // comparing enums to ints directly throws a warning
  323. FIRInstanceIDErrorCode noError = INT_MAX;
  324. FIRInstanceIDErrorCode errorCode = noError;
  325. if (![authorizedEntity length]) {
  326. errorCode = kFIRInstanceIDErrorCodeInvalidAuthorizedEntity;
  327. } else if (![scope length]) {
  328. errorCode = kFIRInstanceIDErrorCodeInvalidScope;
  329. } else if (!self.installations) {
  330. errorCode = kFIRInstanceIDErrorCodeInvalidStart;
  331. }
  332. FIRInstanceIDDeleteTokenHandler newHandler = ^(NSError *error) {
  333. // If a default token is deleted successfully, reset the defaultFCMToken too.
  334. if (!error && [authorizedEntity isEqualToString:self.fcmSenderID] &&
  335. [scope isEqualToString:kFIRInstanceIDDefaultTokenScope]) {
  336. self.defaultFCMToken = nil;
  337. }
  338. dispatch_async(dispatch_get_main_queue(), ^{
  339. handler(error);
  340. });
  341. };
  342. if (errorCode != noError) {
  343. newHandler([NSError errorWithFIRInstanceIDErrorCode:errorCode]);
  344. return;
  345. }
  346. FIRInstanceID_WEAKIFY(self);
  347. FIRInstanceIDAuthService *authService = self.tokenManager.authService;
  348. [authService
  349. fetchCheckinInfoWithHandler:^(FIRInstanceIDCheckinPreferences *preferences, NSError *error) {
  350. FIRInstanceID_STRONGIFY(self);
  351. if (error) {
  352. newHandler(error);
  353. return;
  354. }
  355. FIRInstanceID_WEAKIFY(self);
  356. [self.installations installationIDWithCompletion:^(NSString *_Nullable identifier,
  357. NSError *_Nullable error) {
  358. FIRInstanceID_STRONGIFY(self);
  359. if (error) {
  360. NSError *newError =
  361. [NSError errorWithFIRInstanceIDErrorCode:kFIRInstanceIDErrorCodeInvalidKeyPair];
  362. newHandler(newError);
  363. } else {
  364. [self.tokenManager deleteTokenWithAuthorizedEntity:authorizedEntity
  365. scope:scope
  366. instanceID:identifier
  367. handler:newHandler];
  368. }
  369. }];
  370. }];
  371. }
  372. #pragma mark - Identity
  373. - (void)getIDWithHandler:(FIRInstanceIDHandler)handler {
  374. if (!handler) {
  375. FIRInstanceIDLoggerError(kFIRInstanceIDMessageCodeInstanceID003,
  376. kFIRInstanceIDInvalidNilHandlerError);
  377. return;
  378. }
  379. FIRInstanceID_WEAKIFY(self);
  380. [self.installations
  381. installationIDWithCompletion:^(NSString *_Nullable identifier, NSError *_Nullable error) {
  382. FIRInstanceID_STRONGIFY(self);
  383. // When getID is explicitly called, trigger getToken to make sure token always exists.
  384. // This is to avoid ID conflict (ID is not checked for conflict until we generate a token)
  385. if (identifier) {
  386. [self token];
  387. }
  388. handler(identifier, error);
  389. }];
  390. }
  391. - (void)deleteIDWithHandler:(FIRInstanceIDDeleteHandler)handler {
  392. if (!handler) {
  393. FIRInstanceIDLoggerError(kFIRInstanceIDMessageCodeInstanceID004,
  394. kFIRInstanceIDInvalidNilHandlerError);
  395. return;
  396. }
  397. void (^callHandlerOnMainThread)(NSError *) = ^(NSError *error) {
  398. if ([NSThread isMainThread]) {
  399. handler(error);
  400. return;
  401. }
  402. dispatch_async(dispatch_get_main_queue(), ^{
  403. handler(error);
  404. });
  405. };
  406. if (!self.installations) {
  407. FIRInstanceIDErrorCode error = kFIRInstanceIDErrorCodeInvalidStart;
  408. callHandlerOnMainThread([NSError errorWithFIRInstanceIDErrorCode:error]);
  409. return;
  410. }
  411. FIRInstanceID_WEAKIFY(self);
  412. void (^deleteTokensHandler)(NSError *) = ^void(NSError *error) {
  413. FIRInstanceID_STRONGIFY(self);
  414. if (error) {
  415. callHandlerOnMainThread(error);
  416. return;
  417. }
  418. [self deleteIdentityWithHandler:^(NSError *error) {
  419. callHandlerOnMainThread(error);
  420. }];
  421. };
  422. [self.installations
  423. installationIDWithCompletion:^(NSString *_Nullable identifier, NSError *_Nullable error) {
  424. FIRInstanceID_STRONGIFY(self);
  425. if (error) {
  426. NSError *newError =
  427. [NSError errorWithFIRInstanceIDErrorCode:kFIRInstanceIDErrorCodeInvalidKeyPair];
  428. callHandlerOnMainThread(newError);
  429. } else {
  430. [self.tokenManager deleteAllTokensWithInstanceID:identifier handler:deleteTokensHandler];
  431. }
  432. }];
  433. }
  434. - (void)notifyIdentityReset {
  435. [self deleteIdentityWithHandler:nil];
  436. }
  437. // Delete all the local cache checkin, IID and token.
  438. - (void)deleteIdentityWithHandler:(FIRInstanceIDDeleteHandler)handler {
  439. // Delete tokens.
  440. [self.tokenManager deleteAllTokensLocallyWithHandler:^(NSError *deleteTokenError) {
  441. // Reset FCM token.
  442. self.defaultFCMToken = nil;
  443. if (deleteTokenError) {
  444. if (handler) {
  445. handler(deleteTokenError);
  446. }
  447. return;
  448. }
  449. // Delete Instance ID.
  450. [self.installations deleteWithCompletion:^(NSError *_Nullable error) {
  451. if (error) {
  452. if (handler) {
  453. handler(error);
  454. }
  455. return;
  456. }
  457. [self.tokenManager.authService resetCheckinWithHandler:^(NSError *error) {
  458. if (error) {
  459. if (handler) {
  460. handler(error);
  461. }
  462. return;
  463. }
  464. // Only request new token if FCM auto initialization is
  465. // enabled.
  466. if ([self isFCMAutoInitEnabled]) {
  467. // Deletion succeeds! Requesting new checkin, IID and token.
  468. // TODO(chliangGoogle) see if dispatch_after is necessary
  469. dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.5 * NSEC_PER_SEC)),
  470. dispatch_get_main_queue(), ^{
  471. [self defaultTokenWithHandler:nil];
  472. });
  473. }
  474. if (handler) {
  475. handler(nil);
  476. }
  477. }];
  478. }];
  479. }];
  480. }
  481. #pragma mark - Checkin
  482. - (BOOL)tryToLoadValidCheckinInfo {
  483. FIRInstanceIDCheckinPreferences *checkinPreferences =
  484. [self.tokenManager.authService checkinPreferences];
  485. return [checkinPreferences hasValidCheckinInfo];
  486. }
  487. - (NSString *)deviceAuthID {
  488. return [self.tokenManager.authService checkinPreferences].deviceID;
  489. }
  490. - (NSString *)secretToken {
  491. return [self.tokenManager.authService checkinPreferences].secretToken;
  492. }
  493. - (NSString *)versionInfo {
  494. return [self.tokenManager.authService checkinPreferences].versionInfo;
  495. }
  496. #pragma mark - Config
  497. + (void)load {
  498. [FIRApp registerInternalLibrary:(Class<FIRLibrary>)self
  499. withName:@"fire-iid"
  500. withVersion:FIRInstanceIDCurrentLibraryVersion()];
  501. }
  502. + (nonnull NSArray<FIRComponent *> *)componentsToRegister {
  503. FIRComponentCreationBlock creationBlock =
  504. ^id _Nullable(FIRComponentContainer *container, BOOL *isCacheable) {
  505. // InstanceID only works with the default app.
  506. if (!container.app.isDefaultApp) {
  507. // Only configure for the default FIRApp.
  508. FIRInstanceIDLoggerDebug(kFIRInstanceIDMessageCodeFIRApp002,
  509. @"Firebase Instance ID only works with the default app.");
  510. return nil;
  511. }
  512. // Ensure it's cached so it returns the same instance every time instanceID is called.
  513. *isCacheable = YES;
  514. FIRInstanceID *instanceID = [[FIRInstanceID alloc] initPrivately];
  515. [instanceID start];
  516. [instanceID configureInstanceIDWithOptions:container.app.options];
  517. return instanceID;
  518. };
  519. FIRComponent *instanceIDProvider =
  520. [FIRComponent componentWithProtocol:@protocol(FIRInstanceIDInstanceProvider)
  521. instantiationTiming:FIRInstantiationTimingEagerInDefaultApp
  522. dependencies:@[]
  523. creationBlock:creationBlock];
  524. return @[ instanceIDProvider ];
  525. }
  526. - (void)configureInstanceIDWithOptions:(FIROptions *)options {
  527. NSString *GCMSenderID = options.GCMSenderID;
  528. if (!GCMSenderID.length) {
  529. FIRInstanceIDLoggerError(kFIRInstanceIDMessageCodeFIRApp000,
  530. @"Firebase not set up correctly, nil or empty senderID.");
  531. [NSException raise:kFIRIIDErrorDomain
  532. format:@"Could not configure Firebase InstanceID. GCMSenderID must not be nil or "
  533. @"empty."];
  534. }
  535. self.fcmSenderID = GCMSenderID;
  536. self.firebaseAppID = options.googleAppID;
  537. [self updateFirebaseInstallationID];
  538. // FCM generates a FCM token during app start for sending push notification to device.
  539. // This is not needed for app extension except for watch.
  540. #if TARGET_OS_WATCH
  541. [self didCompleteConfigure];
  542. #else
  543. if (![GULAppEnvironmentUtil isAppExtension]) {
  544. [self didCompleteConfigure];
  545. }
  546. #endif
  547. }
  548. // This is used to start any operations when we receive FirebaseSDK setup notification
  549. // from FIRCore.
  550. - (void)didCompleteConfigure {
  551. NSString *cachedToken = [self cachedTokenIfAvailable];
  552. // When there is a cached token, do the token refresh.
  553. if (cachedToken) {
  554. // Clean up expired tokens by checking the token refresh policy.
  555. [self.installations
  556. installationIDWithCompletion:^(NSString *_Nullable identifier, NSError *_Nullable error) {
  557. if ([self.tokenManager checkTokenRefreshPolicyWithIID:identifier]) {
  558. // Default token is expired, fetch default token from server.
  559. [self defaultTokenWithHandler:nil];
  560. }
  561. // Notify FCM with the default token.
  562. self.defaultFCMToken = [self token];
  563. }];
  564. } else if ([self isFCMAutoInitEnabled]) {
  565. // When there is no cached token, must check auto init is enabled.
  566. // If it's disabled, don't initiate token generation/refresh.
  567. // If no cache token and auto init is enabled, fetch a token from server.
  568. [self defaultTokenWithHandler:nil];
  569. // Notify FCM with the default token.
  570. self.defaultFCMToken = [self token];
  571. }
  572. // ONLY checkin when auto data collection is turned on.
  573. if ([self isFCMAutoInitEnabled]) {
  574. [self.tokenManager.authService scheduleCheckin:YES];
  575. }
  576. }
  577. - (BOOL)isFCMAutoInitEnabled {
  578. Class messagingClass = NSClassFromString(kFIRInstanceIDFCMSDKClassString);
  579. // Firebase Messaging is not installed, auto init should be disabled since it's for FCM.
  580. if (!messagingClass) {
  581. return NO;
  582. }
  583. // Messaging doesn't have the class method, auto init should be enabled since FCM exists.
  584. SEL autoInitSelector = NSSelectorFromString(kFIRInstanceIDFCMSelectorAutoInitEnabled);
  585. if (![messagingClass respondsToSelector:autoInitSelector]) {
  586. return YES;
  587. }
  588. // Get the autoInitEnabled class method.
  589. IMP isAutoInitEnabledIMP = [messagingClass methodForSelector:autoInitSelector];
  590. BOOL(*isAutoInitEnabled)
  591. (Class, SEL, GULUserDefaults *) = (BOOL(*)(id, SEL, GULUserDefaults *))isAutoInitEnabledIMP;
  592. // Check FCM's isAutoInitEnabled property.
  593. return isAutoInitEnabled(messagingClass, autoInitSelector,
  594. [GULUserDefaults standardUserDefaults]);
  595. }
  596. // Actually makes InstanceID instantiate both the IID and Token-related subsystems.
  597. - (void)start {
  598. if (![FIRInstanceIDStore hasSubDirectory:kFIRInstanceIDSubDirectoryName]) {
  599. [FIRInstanceIDStore createSubDirectory:kFIRInstanceIDSubDirectoryName];
  600. }
  601. [self setupTokenManager];
  602. self.installations = [FIRInstallations installations];
  603. [self setupNotificationListeners];
  604. }
  605. // Creates the token manager, which is used for fetching, caching, and retrieving tokens.
  606. - (void)setupTokenManager {
  607. self.tokenManager = [[FIRInstanceIDTokenManager alloc] init];
  608. }
  609. - (void)setupNotificationListeners {
  610. // To prevent double notifications remove observer from all events during setup.
  611. NSNotificationCenter *center = [NSNotificationCenter defaultCenter];
  612. [center removeObserver:self];
  613. [center addObserver:self
  614. selector:@selector(notifyIdentityReset)
  615. name:kFIRInstanceIDIdentityInvalidatedNotification
  616. object:nil];
  617. [center addObserver:self
  618. selector:@selector(notifyAPNSTokenIsSet:)
  619. name:kFIRInstanceIDAPNSTokenNotification
  620. object:nil];
  621. [self observeFirebaseInstallationIDChanges];
  622. }
  623. #pragma mark - Private Helpers
  624. /// Maximum retry count to fetch the default token.
  625. + (int64_t)maxRetryCountForDefaultToken {
  626. return kMaxRetryCountForDefaultToken;
  627. }
  628. /// Minimum interval in seconds between retries to fetch the default token.
  629. + (int64_t)minIntervalForDefaultTokenRetry {
  630. return kMinRetryIntervalForDefaultTokenInSeconds;
  631. }
  632. /// Maximum retry interval between retries to fetch default token.
  633. + (int64_t)maxRetryIntervalForDefaultTokenInSeconds {
  634. return kMaxRetryIntervalForDefaultTokenInSeconds;
  635. }
  636. - (NSInteger)retryIntervalToFetchDefaultToken {
  637. if (self.retryCountForDefaultToken >= [[self class] maxRetryCountForDefaultToken]) {
  638. return (NSInteger)[[self class] maxRetryIntervalForDefaultTokenInSeconds];
  639. }
  640. // exponential backoff with a fixed initial retry time
  641. // 11s, 22s, 44s, 88s ...
  642. int64_t minInterval = [[self class] minIntervalForDefaultTokenRetry];
  643. return (NSInteger)MIN(
  644. (1 << self.retryCountForDefaultToken) + minInterval * self.retryCountForDefaultToken,
  645. kMaxRetryIntervalForDefaultTokenInSeconds);
  646. }
  647. - (void)defaultTokenWithHandler:(nullable FIRInstanceIDTokenHandler)aHandler {
  648. [self defaultTokenWithRetry:NO handler:aHandler];
  649. }
  650. /**
  651. * @param retry Indicates if the method is called to perform a retry after a failed attempt.
  652. * If `YES`, then actual token request will be performed even if `self.defaultTokenFetchHandler !=
  653. * nil`
  654. */
  655. - (void)defaultTokenWithRetry:(BOOL)retry handler:(nullable FIRInstanceIDTokenHandler)aHandler {
  656. BOOL shouldPerformRequest = retry || self.defaultTokenFetchHandler == nil;
  657. if (!self.defaultTokenFetchHandler) {
  658. self.defaultTokenFetchHandler = [[FIRInstanceIDCombinedHandler<NSString *> alloc] init];
  659. }
  660. if (aHandler) {
  661. [self.defaultTokenFetchHandler addHandler:aHandler];
  662. }
  663. if (!shouldPerformRequest) {
  664. return;
  665. }
  666. NSDictionary *instanceIDOptions = @{};
  667. BOOL hasFirebaseMessaging = NSClassFromString(kFIRInstanceIDFCMSDKClassString) != nil;
  668. if (hasFirebaseMessaging && self.apnsTokenData) {
  669. BOOL isSandboxApp = (self.apnsTokenType == FIRInstanceIDAPNSTokenTypeSandbox);
  670. if (self.apnsTokenType == FIRInstanceIDAPNSTokenTypeUnknown) {
  671. isSandboxApp = [self isSandboxApp];
  672. }
  673. instanceIDOptions = @{
  674. kFIRInstanceIDTokenOptionsAPNSKey : self.apnsTokenData,
  675. kFIRInstanceIDTokenOptionsAPNSIsSandboxKey : @(isSandboxApp),
  676. };
  677. }
  678. FIRInstanceID_WEAKIFY(self);
  679. FIRInstanceIDTokenHandler newHandler = ^void(NSString *token, NSError *error) {
  680. FIRInstanceID_STRONGIFY(self);
  681. if (error) {
  682. FIRInstanceIDLoggerError(kFIRInstanceIDMessageCodeInstanceID009,
  683. @"Failed to fetch default token %@", error);
  684. // This notification can be sent multiple times since we can't guarantee success at any point
  685. // of time.
  686. NSNotification *tokenFetchFailNotification =
  687. [NSNotification notificationWithName:kFIRInstanceIDDefaultGCMTokenFailNotification
  688. object:[error copy]];
  689. [[NSNotificationQueue defaultQueue] enqueueNotification:tokenFetchFailNotification
  690. postingStyle:NSPostASAP];
  691. self.retryCountForDefaultToken = (NSInteger)MIN(self.retryCountForDefaultToken + 1,
  692. [[self class] maxRetryCountForDefaultToken]);
  693. // Do not retry beyond the maximum limit.
  694. if (self.retryCountForDefaultToken < [[self class] maxRetryCountForDefaultToken]) {
  695. NSInteger retryInterval = [self retryIntervalToFetchDefaultToken];
  696. [self retryGetDefaultTokenAfter:retryInterval];
  697. } else {
  698. FIRInstanceIDLoggerError(kFIRInstanceIDMessageCodeInstanceID007,
  699. @"Failed to retrieve the default FCM token after %ld retries",
  700. (long)self.retryCountForDefaultToken);
  701. [self performDefaultTokenHandlerWithToken:nil error:error];
  702. }
  703. } else {
  704. // If somebody updated IID with APNS token while our initial request did not have it
  705. // set we need to update it on the server.
  706. NSData *deviceTokenInRequest = instanceIDOptions[kFIRInstanceIDTokenOptionsAPNSKey];
  707. BOOL isSandboxInRequest =
  708. [instanceIDOptions[kFIRInstanceIDTokenOptionsAPNSIsSandboxKey] boolValue];
  709. // Note that APNSTupleStringInRequest will be nil if deviceTokenInRequest is nil
  710. NSString *APNSTupleStringInRequest = FIRInstanceIDAPNSTupleStringForTokenAndServerType(
  711. deviceTokenInRequest, isSandboxInRequest);
  712. // If the APNs value either remained nil, or was the same non-nil value, the APNs value
  713. // did not change.
  714. BOOL APNSRemainedSameDuringFetch =
  715. (self.APNSTupleString == nil && APNSTupleStringInRequest == nil) ||
  716. ([self.APNSTupleString isEqualToString:APNSTupleStringInRequest]);
  717. if (!APNSRemainedSameDuringFetch && hasFirebaseMessaging) {
  718. // APNs value did change mid-fetch, so the token should be re-fetched with the current APNs
  719. // value.
  720. [self retryGetDefaultTokenAfter:0];
  721. FIRInstanceIDLoggerDebug(kFIRInstanceIDMessageCodeRefetchingTokenForAPNS,
  722. @"Received APNS token while fetching default token. "
  723. @"Refetching default token.");
  724. // Do not notify and handle completion handler since this is a retry.
  725. // Simply return.
  726. return;
  727. } else {
  728. FIRInstanceIDLoggerInfo(kFIRInstanceIDMessageCodeInstanceID010,
  729. @"Successfully fetched default token.");
  730. }
  731. // Post the required notifications if somebody is waiting.
  732. FIRInstanceIDLoggerDebug(kFIRInstanceIDMessageCodeInstanceID008, @"Got default token %@",
  733. token);
  734. NSString *previousFCMToken = self.defaultFCMToken;
  735. self.defaultFCMToken = token;
  736. // Only notify of token refresh if we have a new valid token that's different than before
  737. if (self.defaultFCMToken.length && ![self.defaultFCMToken isEqualToString:previousFCMToken]) {
  738. NSNotification *tokenRefreshNotification =
  739. [NSNotification notificationWithName:kFIRInstanceIDTokenRefreshNotification
  740. object:[self.defaultFCMToken copy]];
  741. [[NSNotificationQueue defaultQueue] enqueueNotification:tokenRefreshNotification
  742. postingStyle:NSPostASAP];
  743. }
  744. [self performDefaultTokenHandlerWithToken:token error:nil];
  745. }
  746. };
  747. [self tokenWithAuthorizedEntity:self.fcmSenderID
  748. scope:kFIRInstanceIDDefaultTokenScope
  749. options:instanceIDOptions
  750. handler:newHandler];
  751. }
  752. /**
  753. *
  754. */
  755. - (void)performDefaultTokenHandlerWithToken:(NSString *)token error:(NSError *)error {
  756. if (!self.defaultTokenFetchHandler) {
  757. return;
  758. }
  759. [self.defaultTokenFetchHandler combinedHandler](token, error);
  760. self.defaultTokenFetchHandler = nil;
  761. }
  762. - (void)retryGetDefaultTokenAfter:(NSTimeInterval)retryInterval {
  763. FIRInstanceID_WEAKIFY(self);
  764. dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(retryInterval * NSEC_PER_SEC)),
  765. dispatch_get_main_queue(), ^{
  766. FIRInstanceID_STRONGIFY(self);
  767. // Pass nil: no new handlers to be added, currently existing handlers
  768. // will be called
  769. [self defaultTokenWithRetry:YES handler:nil];
  770. });
  771. }
  772. #pragma mark - APNS Token
  773. // This should only be triggered from FCM.
  774. - (void)notifyAPNSTokenIsSet:(NSNotification *)notification {
  775. NSData *token = notification.object;
  776. if (!token || ![token isKindOfClass:[NSData class]]) {
  777. FIRInstanceIDLoggerDebug(kFIRInstanceIDMessageCodeInternal002, @"Invalid APNS token type %@",
  778. NSStringFromClass([notification.object class]));
  779. return;
  780. }
  781. NSInteger type = [notification.userInfo[kFIRInstanceIDAPNSTokenType] integerValue];
  782. // The APNS token is being added, or has changed (rare)
  783. if ([self.apnsTokenData isEqualToData:token]) {
  784. FIRInstanceIDLoggerDebug(kFIRInstanceIDMessageCodeInstanceID011,
  785. @"Trying to reset APNS token to the same value. Will return");
  786. return;
  787. }
  788. // Use this token type for when we have to automatically fetch tokens in the future
  789. self.apnsTokenType = type;
  790. BOOL isSandboxApp = (type == FIRInstanceIDAPNSTokenTypeSandbox);
  791. if (self.apnsTokenType == FIRInstanceIDAPNSTokenTypeUnknown) {
  792. isSandboxApp = [self isSandboxApp];
  793. }
  794. self.apnsTokenData = [token copy];
  795. self.APNSTupleString = FIRInstanceIDAPNSTupleStringForTokenAndServerType(token, isSandboxApp);
  796. // Pro-actively invalidate the default token, if the APNs change makes it
  797. // invalid. Previously, we invalidated just before fetching the token.
  798. NSArray<FIRInstanceIDTokenInfo *> *invalidatedTokens =
  799. [self.tokenManager updateTokensToAPNSDeviceToken:self.apnsTokenData isSandbox:isSandboxApp];
  800. // Re-fetch any invalidated tokens automatically, this time with the current APNs token, so that
  801. // they are up-to-date.
  802. if (invalidatedTokens.count > 0) {
  803. FIRInstanceID_WEAKIFY(self);
  804. [self.installations
  805. installationIDWithCompletion:^(NSString *_Nullable identifier, NSError *_Nullable error) {
  806. FIRInstanceID_STRONGIFY(self);
  807. if (self == nil) {
  808. FIRInstanceIDLoggerError(kFIRInstanceIDMessageCodeInstanceID017,
  809. @"Instance ID shut down during token reset. Aborting");
  810. return;
  811. }
  812. if (self.apnsTokenData == nil) {
  813. FIRInstanceIDLoggerError(kFIRInstanceIDMessageCodeInstanceID018,
  814. @"apnsTokenData was set to nil during token reset. Aborting");
  815. return;
  816. }
  817. NSMutableDictionary *tokenOptions = [@{
  818. kFIRInstanceIDTokenOptionsAPNSKey : self.apnsTokenData,
  819. kFIRInstanceIDTokenOptionsAPNSIsSandboxKey : @(isSandboxApp)
  820. } mutableCopy];
  821. if (self.firebaseAppID) {
  822. tokenOptions[kFIRInstanceIDTokenOptionsFirebaseAppIDKey] = self.firebaseAppID;
  823. }
  824. for (FIRInstanceIDTokenInfo *tokenInfo in invalidatedTokens) {
  825. if ([tokenInfo.token isEqualToString:self.defaultFCMToken]) {
  826. // We will perform a special fetch for the default FCM token, so that the delegate
  827. // methods are called. For all others, we will do an internal re-fetch.
  828. [self defaultTokenWithHandler:nil];
  829. } else {
  830. [self.tokenManager fetchNewTokenWithAuthorizedEntity:tokenInfo.authorizedEntity
  831. scope:tokenInfo.scope
  832. instanceID:identifier
  833. options:tokenOptions
  834. handler:^(NSString *_Nullable token,
  835. NSError *_Nullable error){
  836. }];
  837. }
  838. }
  839. }];
  840. }
  841. }
  842. - (BOOL)isSandboxApp {
  843. static BOOL isSandboxApp = YES;
  844. static dispatch_once_t onceToken;
  845. dispatch_once(&onceToken, ^{
  846. isSandboxApp = ![self isProductionApp];
  847. });
  848. return isSandboxApp;
  849. }
  850. - (BOOL)isProductionApp {
  851. const BOOL defaultAppTypeProd = YES;
  852. NSError *error = nil;
  853. if ([GULAppEnvironmentUtil isSimulator]) {
  854. [self logAPNSConfigurationError:@"Running InstanceID on a simulator doesn't have APNS. "
  855. @"Use prod profile by default."];
  856. return defaultAppTypeProd;
  857. }
  858. if ([GULAppEnvironmentUtil isFromAppStore]) {
  859. // Apps distributed via AppStore or TestFlight use the Production APNS certificates.
  860. return defaultAppTypeProd;
  861. }
  862. #if TARGET_OS_IOS || TARGET_OS_TV || TARGET_OS_WATCH
  863. NSString *path = [[[NSBundle mainBundle] bundlePath]
  864. stringByAppendingPathComponent:@"embedded.mobileprovision"];
  865. #elif TARGET_OS_OSX
  866. NSString *path = [[[[NSBundle mainBundle] resourcePath] stringByDeletingLastPathComponent]
  867. stringByAppendingPathComponent:@"embedded.provisionprofile"];
  868. #endif
  869. if ([GULAppEnvironmentUtil isAppStoreReceiptSandbox] && !path.length) {
  870. // Distributed via TestFlight
  871. return defaultAppTypeProd;
  872. }
  873. NSMutableData *profileData = [NSMutableData dataWithContentsOfFile:path options:0 error:&error];
  874. if (!profileData.length || error) {
  875. NSString *errorString =
  876. [NSString stringWithFormat:@"Error while reading embedded mobileprovision %@", error];
  877. [self logAPNSConfigurationError:errorString];
  878. return defaultAppTypeProd;
  879. }
  880. // The "embedded.mobileprovision" sometimes contains characters with value 0, which signals the
  881. // end of a c-string and halts the ASCII parser, or with value > 127, which violates strict 7-bit
  882. // ASCII. Replace any 0s or invalid characters in the input.
  883. uint8_t *profileBytes = (uint8_t *)profileData.bytes;
  884. for (int i = 0; i < profileData.length; i++) {
  885. uint8_t currentByte = profileBytes[i];
  886. if (!currentByte || currentByte > 127) {
  887. profileBytes[i] = '.';
  888. }
  889. }
  890. NSString *embeddedProfile = [[NSString alloc] initWithBytesNoCopy:profileBytes
  891. length:profileData.length
  892. encoding:NSASCIIStringEncoding
  893. freeWhenDone:NO];
  894. if (error || !embeddedProfile.length) {
  895. NSString *errorString =
  896. [NSString stringWithFormat:@"Error while reading embedded mobileprovision %@", error];
  897. [self logAPNSConfigurationError:errorString];
  898. return defaultAppTypeProd;
  899. }
  900. NSScanner *scanner = [NSScanner scannerWithString:embeddedProfile];
  901. NSString *plistContents;
  902. if ([scanner scanUpToString:@"<plist" intoString:nil]) {
  903. if ([scanner scanUpToString:@"</plist>" intoString:&plistContents]) {
  904. plistContents = [plistContents stringByAppendingString:@"</plist>"];
  905. }
  906. }
  907. if (!plistContents.length) {
  908. return defaultAppTypeProd;
  909. }
  910. NSData *data = [plistContents dataUsingEncoding:NSUTF8StringEncoding];
  911. if (!data.length) {
  912. [self logAPNSConfigurationError:@"Couldn't read plist fetched from embedded mobileprovision"];
  913. return defaultAppTypeProd;
  914. }
  915. NSError *plistMapError;
  916. id plistData = [NSPropertyListSerialization propertyListWithData:data
  917. options:NSPropertyListImmutable
  918. format:nil
  919. error:&plistMapError];
  920. if (plistMapError || ![plistData isKindOfClass:[NSDictionary class]]) {
  921. NSString *errorString =
  922. [NSString stringWithFormat:@"Error while converting assumed plist to dict %@",
  923. plistMapError.localizedDescription];
  924. [self logAPNSConfigurationError:errorString];
  925. return defaultAppTypeProd;
  926. }
  927. NSDictionary *plistMap = (NSDictionary *)plistData;
  928. if ([plistMap valueForKeyPath:@"ProvisionedDevices"]) {
  929. FIRInstanceIDLoggerDebug(kFIRInstanceIDMessageCodeInstanceID012,
  930. @"Provisioning profile has specifically provisioned devices, "
  931. @"most likely a Dev profile.");
  932. }
  933. NSString *apsEnvironment = [plistMap valueForKeyPath:kEntitlementsAPSEnvironmentKey];
  934. NSString *debugString __unused =
  935. [NSString stringWithFormat:@"APNS Environment in profile: %@", apsEnvironment];
  936. FIRInstanceIDLoggerDebug(kFIRInstanceIDMessageCodeInstanceID013, @"%@", debugString);
  937. // No aps-environment in the profile.
  938. if (!apsEnvironment.length) {
  939. [self logAPNSConfigurationError:@"No aps-environment set. If testing on a device APNS is not "
  940. @"correctly configured. Please recheck your provisioning "
  941. @"profiles. If testing on a simulator this is fine since APNS "
  942. @"doesn't work on the simulator."];
  943. return defaultAppTypeProd;
  944. }
  945. if ([apsEnvironment isEqualToString:kAPSEnvironmentDevelopmentValue]) {
  946. return NO;
  947. }
  948. return defaultAppTypeProd;
  949. }
  950. /// Log error messages only when Messaging exists in the pod.
  951. - (void)logAPNSConfigurationError:(NSString *)errorString {
  952. BOOL hasFirebaseMessaging = NSClassFromString(kFIRInstanceIDFCMSDKClassString) != nil;
  953. if (hasFirebaseMessaging) {
  954. FIRInstanceIDLoggerError(kFIRInstanceIDMessageCodeInstanceID014, @"%@", errorString);
  955. } else {
  956. FIRInstanceIDLoggerDebug(kFIRInstanceIDMessageCodeInstanceID015, @"%@", errorString);
  957. }
  958. }
  959. #pragma mark - Sync InstanceID
  960. - (void)updateFirebaseInstallationID {
  961. FIRInstanceID_WEAKIFY(self);
  962. [self.installations
  963. installationIDWithCompletion:^(NSString *_Nullable installationID, NSError *_Nullable error) {
  964. FIRInstanceID_STRONGIFY(self);
  965. self.firebaseInstallationsID = installationID;
  966. }];
  967. }
  968. - (void)installationIDDidChangeNotificationReceived:(NSNotification *)notification {
  969. NSString *installationAppID =
  970. notification.userInfo[kFIRInstallationIDDidChangeNotificationAppNameKey];
  971. if ([installationAppID isKindOfClass:[NSString class]] &&
  972. [installationAppID isEqual:self.firebaseAppID]) {
  973. [self updateFirebaseInstallationID];
  974. }
  975. }
  976. - (void)observeFirebaseInstallationIDChanges {
  977. [[NSNotificationCenter defaultCenter] removeObserver:self
  978. name:FIRInstallationIDDidChangeNotification
  979. object:nil];
  980. [[NSNotificationCenter defaultCenter]
  981. addObserver:self
  982. selector:@selector(installationIDDidChangeNotificationReceived:)
  983. name:FIRInstallationIDDidChangeNotification
  984. object:nil];
  985. }
  986. @end