FIRInstanceID.m 43 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131
  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. return;
  322. }
  323. // comparing enums to ints directly throws a warning
  324. FIRInstanceIDErrorCode noError = INT_MAX;
  325. FIRInstanceIDErrorCode errorCode = noError;
  326. if (![authorizedEntity length]) {
  327. errorCode = kFIRInstanceIDErrorCodeInvalidAuthorizedEntity;
  328. } else if (![scope length]) {
  329. errorCode = kFIRInstanceIDErrorCodeInvalidScope;
  330. } else if (!self.installations) {
  331. errorCode = kFIRInstanceIDErrorCodeInvalidStart;
  332. }
  333. FIRInstanceIDDeleteTokenHandler newHandler = ^(NSError *error) {
  334. // If a default token is deleted successfully, reset the defaultFCMToken too.
  335. if (!error && [authorizedEntity isEqualToString:self.fcmSenderID] &&
  336. [scope isEqualToString:kFIRInstanceIDDefaultTokenScope]) {
  337. self.defaultFCMToken = nil;
  338. }
  339. dispatch_async(dispatch_get_main_queue(), ^{
  340. handler(error);
  341. });
  342. };
  343. if (errorCode != noError) {
  344. newHandler([NSError errorWithFIRInstanceIDErrorCode:errorCode]);
  345. return;
  346. }
  347. FIRInstanceID_WEAKIFY(self);
  348. FIRInstanceIDAuthService *authService = self.tokenManager.authService;
  349. [authService
  350. fetchCheckinInfoWithHandler:^(FIRInstanceIDCheckinPreferences *preferences, NSError *error) {
  351. FIRInstanceID_STRONGIFY(self);
  352. if (error) {
  353. newHandler(error);
  354. return;
  355. }
  356. FIRInstanceID_WEAKIFY(self);
  357. [self.installations installationIDWithCompletion:^(NSString *_Nullable identifier,
  358. NSError *_Nullable error) {
  359. FIRInstanceID_STRONGIFY(self);
  360. if (error) {
  361. NSError *newError =
  362. [NSError errorWithFIRInstanceIDErrorCode:kFIRInstanceIDErrorCodeInvalidKeyPair];
  363. newHandler(newError);
  364. } else {
  365. [self.tokenManager deleteTokenWithAuthorizedEntity:authorizedEntity
  366. scope:scope
  367. instanceID:identifier
  368. handler:newHandler];
  369. }
  370. }];
  371. }];
  372. }
  373. #pragma mark - Identity
  374. - (void)getIDWithHandler:(FIRInstanceIDHandler)handler {
  375. if (!handler) {
  376. FIRInstanceIDLoggerError(kFIRInstanceIDMessageCodeInstanceID003,
  377. kFIRInstanceIDInvalidNilHandlerError);
  378. return;
  379. }
  380. FIRInstanceID_WEAKIFY(self);
  381. [self.installations
  382. installationIDWithCompletion:^(NSString *_Nullable identifier, NSError *_Nullable error) {
  383. FIRInstanceID_STRONGIFY(self);
  384. // When getID is explicitly called, trigger getToken to make sure token always exists.
  385. // This is to avoid ID conflict (ID is not checked for conflict until we generate a token)
  386. if (identifier) {
  387. [self token];
  388. }
  389. handler(identifier, error);
  390. }];
  391. }
  392. - (void)deleteIDWithHandler:(FIRInstanceIDDeleteHandler)handler {
  393. if (!handler) {
  394. FIRInstanceIDLoggerError(kFIRInstanceIDMessageCodeInstanceID004,
  395. kFIRInstanceIDInvalidNilHandlerError);
  396. return;
  397. }
  398. void (^callHandlerOnMainThread)(NSError *) = ^(NSError *error) {
  399. if ([NSThread isMainThread]) {
  400. handler(error);
  401. return;
  402. }
  403. dispatch_async(dispatch_get_main_queue(), ^{
  404. handler(error);
  405. });
  406. };
  407. if (!self.installations) {
  408. FIRInstanceIDErrorCode error = kFIRInstanceIDErrorCodeInvalidStart;
  409. callHandlerOnMainThread([NSError errorWithFIRInstanceIDErrorCode:error]);
  410. return;
  411. }
  412. FIRInstanceID_WEAKIFY(self);
  413. void (^deleteTokensHandler)(NSError *) = ^void(NSError *error) {
  414. FIRInstanceID_STRONGIFY(self);
  415. if (error) {
  416. callHandlerOnMainThread(error);
  417. return;
  418. }
  419. [self deleteIdentityWithHandler:^(NSError *error) {
  420. callHandlerOnMainThread(error);
  421. }];
  422. };
  423. [self.installations
  424. installationIDWithCompletion:^(NSString *_Nullable identifier, NSError *_Nullable error) {
  425. FIRInstanceID_STRONGIFY(self);
  426. if (error) {
  427. NSError *newError =
  428. [NSError errorWithFIRInstanceIDErrorCode:kFIRInstanceIDErrorCodeInvalidKeyPair];
  429. callHandlerOnMainThread(newError);
  430. } else {
  431. [self.tokenManager deleteAllTokensWithInstanceID:identifier handler:deleteTokensHandler];
  432. }
  433. }];
  434. }
  435. - (void)notifyIdentityReset {
  436. [self deleteIdentityWithHandler:nil];
  437. }
  438. // Delete all the local cache checkin, IID and token.
  439. - (void)deleteIdentityWithHandler:(FIRInstanceIDDeleteHandler)handler {
  440. // Delete tokens.
  441. [self.tokenManager deleteAllTokensLocallyWithHandler:^(NSError *deleteTokenError) {
  442. // Reset FCM token.
  443. self.defaultFCMToken = nil;
  444. if (deleteTokenError) {
  445. if (handler) {
  446. handler(deleteTokenError);
  447. }
  448. return;
  449. }
  450. // Delete Instance ID.
  451. [self.installations deleteWithCompletion:^(NSError *_Nullable error) {
  452. if (error) {
  453. if (handler) {
  454. handler(error);
  455. }
  456. return;
  457. }
  458. [self.tokenManager.authService resetCheckinWithHandler:^(NSError *error) {
  459. if (error) {
  460. if (handler) {
  461. handler(error);
  462. }
  463. return;
  464. }
  465. // Only request new token if FCM auto initialization is
  466. // enabled.
  467. if ([self isFCMAutoInitEnabled]) {
  468. // Deletion succeeds! Requesting new checkin, IID and token.
  469. // TODO(chliangGoogle) see if dispatch_after is necessary
  470. dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.5 * NSEC_PER_SEC)),
  471. dispatch_get_main_queue(), ^{
  472. [self defaultTokenWithHandler:nil];
  473. });
  474. }
  475. if (handler) {
  476. handler(nil);
  477. }
  478. }];
  479. }];
  480. }];
  481. }
  482. #pragma mark - Checkin
  483. - (BOOL)tryToLoadValidCheckinInfo {
  484. FIRInstanceIDCheckinPreferences *checkinPreferences =
  485. [self.tokenManager.authService checkinPreferences];
  486. return [checkinPreferences hasValidCheckinInfo];
  487. }
  488. - (NSString *)deviceAuthID {
  489. return [self.tokenManager.authService checkinPreferences].deviceID;
  490. }
  491. - (NSString *)secretToken {
  492. return [self.tokenManager.authService checkinPreferences].secretToken;
  493. }
  494. - (NSString *)versionInfo {
  495. return [self.tokenManager.authService checkinPreferences].versionInfo;
  496. }
  497. #pragma mark - Config
  498. + (void)load {
  499. [FIRApp registerInternalLibrary:(Class<FIRLibrary>)self
  500. withName:@"fire-iid"
  501. withVersion:FIRInstanceIDCurrentLibraryVersion()];
  502. }
  503. + (nonnull NSArray<FIRComponent *> *)componentsToRegister {
  504. FIRComponentCreationBlock creationBlock =
  505. ^id _Nullable(FIRComponentContainer *container, BOOL *isCacheable) {
  506. // InstanceID only works with the default app.
  507. if (!container.app.isDefaultApp) {
  508. // Only configure for the default FIRApp.
  509. FIRInstanceIDLoggerDebug(kFIRInstanceIDMessageCodeFIRApp002,
  510. @"Firebase Instance ID only works with the default app.");
  511. return nil;
  512. }
  513. // Ensure it's cached so it returns the same instance every time instanceID is called.
  514. *isCacheable = YES;
  515. FIRInstanceID *instanceID = [[FIRInstanceID alloc] initPrivately];
  516. [instanceID start];
  517. [instanceID configureInstanceIDWithOptions:container.app.options];
  518. return instanceID;
  519. };
  520. FIRComponent *instanceIDProvider =
  521. [FIRComponent componentWithProtocol:@protocol(FIRInstanceIDInstanceProvider)
  522. instantiationTiming:FIRInstantiationTimingEagerInDefaultApp
  523. dependencies:@[]
  524. creationBlock:creationBlock];
  525. return @[ instanceIDProvider ];
  526. }
  527. - (void)configureInstanceIDWithOptions:(FIROptions *)options {
  528. NSString *GCMSenderID = options.GCMSenderID;
  529. if (!GCMSenderID.length) {
  530. FIRInstanceIDLoggerError(kFIRInstanceIDMessageCodeFIRApp000,
  531. @"Firebase not set up correctly, nil or empty senderID.");
  532. [NSException raise:kFIRIIDErrorDomain
  533. format:@"Could not configure Firebase InstanceID. GCMSenderID must not be nil or "
  534. @"empty."];
  535. }
  536. self.fcmSenderID = GCMSenderID;
  537. self.firebaseAppID = options.googleAppID;
  538. [self updateFirebaseInstallationID];
  539. // FCM generates a FCM token during app start for sending push notification to device.
  540. // This is not needed for app extension except for watch.
  541. #if TARGET_OS_WATCH
  542. [self didCompleteConfigure];
  543. #else
  544. if (![GULAppEnvironmentUtil isAppExtension]) {
  545. [self didCompleteConfigure];
  546. }
  547. #endif
  548. }
  549. // This is used to start any operations when we receive FirebaseSDK setup notification
  550. // from FIRCore.
  551. - (void)didCompleteConfigure {
  552. NSString *cachedToken = [self cachedTokenIfAvailable];
  553. // When there is a cached token, do the token refresh.
  554. if (cachedToken) {
  555. // Clean up expired tokens by checking the token refresh policy.
  556. [self.installations
  557. installationIDWithCompletion:^(NSString *_Nullable identifier, NSError *_Nullable error) {
  558. if ([self.tokenManager checkTokenRefreshPolicyWithIID:identifier]) {
  559. // Default token is expired, fetch default token from server.
  560. [self defaultTokenWithHandler:nil];
  561. }
  562. // Notify FCM with the default token.
  563. self.defaultFCMToken = [self token];
  564. }];
  565. } else if ([self isFCMAutoInitEnabled]) {
  566. // When there is no cached token, must check auto init is enabled.
  567. // If it's disabled, don't initiate token generation/refresh.
  568. // If no cache token and auto init is enabled, fetch a token from server.
  569. [self defaultTokenWithHandler:nil];
  570. // Notify FCM with the default token.
  571. self.defaultFCMToken = [self token];
  572. }
  573. // ONLY checkin when auto data collection is turned on.
  574. if ([self isFCMAutoInitEnabled]) {
  575. [self.tokenManager.authService scheduleCheckin:YES];
  576. }
  577. }
  578. - (BOOL)isFCMAutoInitEnabled {
  579. Class messagingClass = NSClassFromString(kFIRInstanceIDFCMSDKClassString);
  580. // Firebase Messaging is not installed, auto init should be disabled since it's for FCM.
  581. if (!messagingClass) {
  582. return NO;
  583. }
  584. // Messaging doesn't have the class method, auto init should be enabled since FCM exists.
  585. SEL autoInitSelector = NSSelectorFromString(kFIRInstanceIDFCMSelectorAutoInitEnabled);
  586. if (![messagingClass respondsToSelector:autoInitSelector]) {
  587. return YES;
  588. }
  589. // Get the autoInitEnabled class method.
  590. IMP isAutoInitEnabledIMP = [messagingClass methodForSelector:autoInitSelector];
  591. BOOL(*isAutoInitEnabled)
  592. (Class, SEL, GULUserDefaults *) = (BOOL(*)(id, SEL, GULUserDefaults *))isAutoInitEnabledIMP;
  593. // Check FCM's isAutoInitEnabled property.
  594. return isAutoInitEnabled(messagingClass, autoInitSelector,
  595. [GULUserDefaults standardUserDefaults]);
  596. }
  597. // Actually makes InstanceID instantiate both the IID and Token-related subsystems.
  598. - (void)start {
  599. if (![FIRInstanceIDStore hasSubDirectory:kFIRInstanceIDSubDirectoryName]) {
  600. [FIRInstanceIDStore createSubDirectory:kFIRInstanceIDSubDirectoryName];
  601. }
  602. [self setupTokenManager];
  603. self.installations = [FIRInstallations installations];
  604. [self setupNotificationListeners];
  605. }
  606. // Creates the token manager, which is used for fetching, caching, and retrieving tokens.
  607. - (void)setupTokenManager {
  608. self.tokenManager = [[FIRInstanceIDTokenManager alloc] init];
  609. }
  610. - (void)setupNotificationListeners {
  611. // To prevent double notifications remove observer from all events during setup.
  612. NSNotificationCenter *center = [NSNotificationCenter defaultCenter];
  613. [center removeObserver:self];
  614. [center addObserver:self
  615. selector:@selector(notifyIdentityReset)
  616. name:kFIRInstanceIDIdentityInvalidatedNotification
  617. object:nil];
  618. [center addObserver:self
  619. selector:@selector(notifyAPNSTokenIsSet:)
  620. name:kFIRInstanceIDAPNSTokenNotification
  621. object:nil];
  622. [self observeFirebaseInstallationIDChanges];
  623. }
  624. #pragma mark - Private Helpers
  625. /// Maximum retry count to fetch the default token.
  626. + (int64_t)maxRetryCountForDefaultToken {
  627. return kMaxRetryCountForDefaultToken;
  628. }
  629. /// Minimum interval in seconds between retries to fetch the default token.
  630. + (int64_t)minIntervalForDefaultTokenRetry {
  631. return kMinRetryIntervalForDefaultTokenInSeconds;
  632. }
  633. /// Maximum retry interval between retries to fetch default token.
  634. + (int64_t)maxRetryIntervalForDefaultTokenInSeconds {
  635. return kMaxRetryIntervalForDefaultTokenInSeconds;
  636. }
  637. - (NSInteger)retryIntervalToFetchDefaultToken {
  638. if (self.retryCountForDefaultToken >= [[self class] maxRetryCountForDefaultToken]) {
  639. return (NSInteger)[[self class] maxRetryIntervalForDefaultTokenInSeconds];
  640. }
  641. // exponential backoff with a fixed initial retry time
  642. // 11s, 22s, 44s, 88s ...
  643. int64_t minInterval = [[self class] minIntervalForDefaultTokenRetry];
  644. return (NSInteger)MIN(
  645. (1 << self.retryCountForDefaultToken) + minInterval * self.retryCountForDefaultToken,
  646. kMaxRetryIntervalForDefaultTokenInSeconds);
  647. }
  648. - (void)defaultTokenWithHandler:(nullable FIRInstanceIDTokenHandler)aHandler {
  649. [self defaultTokenWithRetry:NO handler:aHandler];
  650. }
  651. /**
  652. * @param retry Indicates if the method is called to perform a retry after a failed attempt.
  653. * If `YES`, then actual token request will be performed even if `self.defaultTokenFetchHandler !=
  654. * nil`
  655. */
  656. - (void)defaultTokenWithRetry:(BOOL)retry handler:(nullable FIRInstanceIDTokenHandler)aHandler {
  657. BOOL shouldPerformRequest = retry || self.defaultTokenFetchHandler == nil;
  658. if (!self.defaultTokenFetchHandler) {
  659. self.defaultTokenFetchHandler = [[FIRInstanceIDCombinedHandler<NSString *> alloc] init];
  660. }
  661. if (aHandler) {
  662. [self.defaultTokenFetchHandler addHandler:aHandler];
  663. }
  664. if (!shouldPerformRequest) {
  665. return;
  666. }
  667. NSDictionary *instanceIDOptions = @{};
  668. BOOL hasFirebaseMessaging = NSClassFromString(kFIRInstanceIDFCMSDKClassString) != nil;
  669. if (hasFirebaseMessaging && self.apnsTokenData) {
  670. BOOL isSandboxApp = (self.apnsTokenType == FIRInstanceIDAPNSTokenTypeSandbox);
  671. if (self.apnsTokenType == FIRInstanceIDAPNSTokenTypeUnknown) {
  672. isSandboxApp = [self isSandboxApp];
  673. }
  674. instanceIDOptions = @{
  675. kFIRInstanceIDTokenOptionsAPNSKey : self.apnsTokenData,
  676. kFIRInstanceIDTokenOptionsAPNSIsSandboxKey : @(isSandboxApp),
  677. };
  678. }
  679. FIRInstanceID_WEAKIFY(self);
  680. FIRInstanceIDTokenHandler newHandler = ^void(NSString *token, NSError *error) {
  681. FIRInstanceID_STRONGIFY(self);
  682. if (error) {
  683. FIRInstanceIDLoggerError(kFIRInstanceIDMessageCodeInstanceID009,
  684. @"Failed to fetch default token %@", error);
  685. // This notification can be sent multiple times since we can't guarantee success at any point
  686. // of time.
  687. NSNotification *tokenFetchFailNotification =
  688. [NSNotification notificationWithName:kFIRInstanceIDDefaultGCMTokenFailNotification
  689. object:[error copy]];
  690. [[NSNotificationQueue defaultQueue] enqueueNotification:tokenFetchFailNotification
  691. postingStyle:NSPostASAP];
  692. self.retryCountForDefaultToken = (NSInteger)MIN(self.retryCountForDefaultToken + 1,
  693. [[self class] maxRetryCountForDefaultToken]);
  694. // Do not retry beyond the maximum limit.
  695. if (self.retryCountForDefaultToken < [[self class] maxRetryCountForDefaultToken]) {
  696. NSInteger retryInterval = [self retryIntervalToFetchDefaultToken];
  697. [self retryGetDefaultTokenAfter:retryInterval];
  698. } else {
  699. FIRInstanceIDLoggerError(kFIRInstanceIDMessageCodeInstanceID007,
  700. @"Failed to retrieve the default FCM token after %ld retries",
  701. (long)self.retryCountForDefaultToken);
  702. [self performDefaultTokenHandlerWithToken:nil error:error];
  703. }
  704. } else {
  705. // If somebody updated IID with APNS token while our initial request did not have it
  706. // set we need to update it on the server.
  707. NSData *deviceTokenInRequest = instanceIDOptions[kFIRInstanceIDTokenOptionsAPNSKey];
  708. BOOL isSandboxInRequest =
  709. [instanceIDOptions[kFIRInstanceIDTokenOptionsAPNSIsSandboxKey] boolValue];
  710. // Note that APNSTupleStringInRequest will be nil if deviceTokenInRequest is nil
  711. NSString *APNSTupleStringInRequest = FIRInstanceIDAPNSTupleStringForTokenAndServerType(
  712. deviceTokenInRequest, isSandboxInRequest);
  713. // If the APNs value either remained nil, or was the same non-nil value, the APNs value
  714. // did not change.
  715. BOOL APNSRemainedSameDuringFetch =
  716. (self.APNSTupleString == nil && APNSTupleStringInRequest == nil) ||
  717. ([self.APNSTupleString isEqualToString:APNSTupleStringInRequest]);
  718. if (!APNSRemainedSameDuringFetch && hasFirebaseMessaging) {
  719. // APNs value did change mid-fetch, so the token should be re-fetched with the current APNs
  720. // value.
  721. [self retryGetDefaultTokenAfter:0];
  722. FIRInstanceIDLoggerDebug(kFIRInstanceIDMessageCodeRefetchingTokenForAPNS,
  723. @"Received APNS token while fetching default token. "
  724. @"Refetching default token.");
  725. // Do not notify and handle completion handler since this is a retry.
  726. // Simply return.
  727. return;
  728. } else {
  729. FIRInstanceIDLoggerInfo(kFIRInstanceIDMessageCodeInstanceID010,
  730. @"Successfully fetched default token.");
  731. }
  732. // Post the required notifications if somebody is waiting.
  733. FIRInstanceIDLoggerDebug(kFIRInstanceIDMessageCodeInstanceID008, @"Got default token %@",
  734. token);
  735. NSString *previousFCMToken = self.defaultFCMToken;
  736. self.defaultFCMToken = token;
  737. // Only notify of token refresh if we have a new valid token that's different than before
  738. if (self.defaultFCMToken.length && ![self.defaultFCMToken isEqualToString:previousFCMToken]) {
  739. NSNotification *tokenRefreshNotification =
  740. [NSNotification notificationWithName:kFIRInstanceIDTokenRefreshNotification
  741. object:[self.defaultFCMToken copy]];
  742. [[NSNotificationQueue defaultQueue] enqueueNotification:tokenRefreshNotification
  743. postingStyle:NSPostASAP];
  744. }
  745. [self performDefaultTokenHandlerWithToken:token error:nil];
  746. }
  747. };
  748. [self tokenWithAuthorizedEntity:self.fcmSenderID
  749. scope:kFIRInstanceIDDefaultTokenScope
  750. options:instanceIDOptions
  751. handler:newHandler];
  752. }
  753. /**
  754. *
  755. */
  756. - (void)performDefaultTokenHandlerWithToken:(NSString *)token error:(NSError *)error {
  757. if (!self.defaultTokenFetchHandler) {
  758. return;
  759. }
  760. [self.defaultTokenFetchHandler combinedHandler](token, error);
  761. self.defaultTokenFetchHandler = nil;
  762. }
  763. - (void)retryGetDefaultTokenAfter:(NSTimeInterval)retryInterval {
  764. FIRInstanceID_WEAKIFY(self);
  765. dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(retryInterval * NSEC_PER_SEC)),
  766. dispatch_get_main_queue(), ^{
  767. FIRInstanceID_STRONGIFY(self);
  768. // Pass nil: no new handlers to be added, currently existing handlers
  769. // will be called
  770. [self defaultTokenWithRetry:YES handler:nil];
  771. });
  772. }
  773. #pragma mark - APNS Token
  774. // This should only be triggered from FCM.
  775. - (void)notifyAPNSTokenIsSet:(NSNotification *)notification {
  776. NSData *token = notification.object;
  777. if (!token || ![token isKindOfClass:[NSData class]]) {
  778. FIRInstanceIDLoggerDebug(kFIRInstanceIDMessageCodeInternal002, @"Invalid APNS token type %@",
  779. NSStringFromClass([notification.object class]));
  780. return;
  781. }
  782. NSInteger type = [notification.userInfo[kFIRInstanceIDAPNSTokenType] integerValue];
  783. // The APNS token is being added, or has changed (rare)
  784. if ([self.apnsTokenData isEqualToData:token]) {
  785. FIRInstanceIDLoggerDebug(kFIRInstanceIDMessageCodeInstanceID011,
  786. @"Trying to reset APNS token to the same value. Will return");
  787. return;
  788. }
  789. // Use this token type for when we have to automatically fetch tokens in the future
  790. self.apnsTokenType = type;
  791. BOOL isSandboxApp = (type == FIRInstanceIDAPNSTokenTypeSandbox);
  792. if (self.apnsTokenType == FIRInstanceIDAPNSTokenTypeUnknown) {
  793. isSandboxApp = [self isSandboxApp];
  794. }
  795. self.apnsTokenData = [token copy];
  796. self.APNSTupleString = FIRInstanceIDAPNSTupleStringForTokenAndServerType(token, isSandboxApp);
  797. // Pro-actively invalidate the default token, if the APNs change makes it
  798. // invalid. Previously, we invalidated just before fetching the token.
  799. NSArray<FIRInstanceIDTokenInfo *> *invalidatedTokens =
  800. [self.tokenManager updateTokensToAPNSDeviceToken:self.apnsTokenData isSandbox:isSandboxApp];
  801. // Re-fetch any invalidated tokens automatically, this time with the current APNs token, so that
  802. // they are up-to-date.
  803. if (invalidatedTokens.count > 0) {
  804. FIRInstanceID_WEAKIFY(self);
  805. [self.installations
  806. installationIDWithCompletion:^(NSString *_Nullable identifier, NSError *_Nullable error) {
  807. FIRInstanceID_STRONGIFY(self);
  808. if (self == nil) {
  809. FIRInstanceIDLoggerError(kFIRInstanceIDMessageCodeInstanceID017,
  810. @"Instance ID shut down during token reset. Aborting");
  811. return;
  812. }
  813. if (self.apnsTokenData == nil) {
  814. FIRInstanceIDLoggerError(kFIRInstanceIDMessageCodeInstanceID018,
  815. @"apnsTokenData was set to nil during token reset. Aborting");
  816. return;
  817. }
  818. NSMutableDictionary *tokenOptions = [@{
  819. kFIRInstanceIDTokenOptionsAPNSKey : self.apnsTokenData,
  820. kFIRInstanceIDTokenOptionsAPNSIsSandboxKey : @(isSandboxApp)
  821. } mutableCopy];
  822. if (self.firebaseAppID) {
  823. tokenOptions[kFIRInstanceIDTokenOptionsFirebaseAppIDKey] = self.firebaseAppID;
  824. }
  825. for (FIRInstanceIDTokenInfo *tokenInfo in invalidatedTokens) {
  826. if ([tokenInfo.token isEqualToString:self.defaultFCMToken]) {
  827. // We will perform a special fetch for the default FCM token, so that the delegate
  828. // methods are called. For all others, we will do an internal re-fetch.
  829. [self defaultTokenWithHandler:nil];
  830. } else {
  831. [self.tokenManager fetchNewTokenWithAuthorizedEntity:tokenInfo.authorizedEntity
  832. scope:tokenInfo.scope
  833. instanceID:identifier
  834. options:tokenOptions
  835. handler:^(NSString *_Nullable token,
  836. NSError *_Nullable error){
  837. }];
  838. }
  839. }
  840. }];
  841. }
  842. }
  843. - (BOOL)isSandboxApp {
  844. static BOOL isSandboxApp = YES;
  845. static dispatch_once_t onceToken;
  846. dispatch_once(&onceToken, ^{
  847. isSandboxApp = ![self isProductionApp];
  848. });
  849. return isSandboxApp;
  850. }
  851. - (BOOL)isProductionApp {
  852. const BOOL defaultAppTypeProd = YES;
  853. NSError *error = nil;
  854. if ([GULAppEnvironmentUtil isSimulator]) {
  855. [self logAPNSConfigurationError:@"Running InstanceID on a simulator doesn't have APNS. "
  856. @"Use prod profile by default."];
  857. return defaultAppTypeProd;
  858. }
  859. if ([GULAppEnvironmentUtil isFromAppStore]) {
  860. // Apps distributed via AppStore or TestFlight use the Production APNS certificates.
  861. return defaultAppTypeProd;
  862. }
  863. #if TARGET_OS_OSX || TARGET_OS_MACCATALYST
  864. NSString *path = [[[[NSBundle mainBundle] resourcePath] stringByDeletingLastPathComponent]
  865. stringByAppendingPathComponent:@"embedded.provisionprofile"];
  866. #elif TARGET_OS_IOS || TARGET_OS_TV || TARGET_OS_WATCH
  867. NSString *path = [[[NSBundle mainBundle] bundlePath]
  868. stringByAppendingPathComponent:@"embedded.mobileprovision"];
  869. #endif
  870. if ([GULAppEnvironmentUtil isAppStoreReceiptSandbox] && !path.length) {
  871. // Distributed via TestFlight
  872. return defaultAppTypeProd;
  873. }
  874. NSMutableData *profileData = [NSMutableData dataWithContentsOfFile:path options:0 error:&error];
  875. if (!profileData.length || error) {
  876. NSString *errorString =
  877. [NSString stringWithFormat:@"Error while reading embedded mobileprovision %@", error];
  878. [self logAPNSConfigurationError:errorString];
  879. return defaultAppTypeProd;
  880. }
  881. // The "embedded.mobileprovision" sometimes contains characters with value 0, which signals the
  882. // end of a c-string and halts the ASCII parser, or with value > 127, which violates strict 7-bit
  883. // ASCII. Replace any 0s or invalid characters in the input.
  884. uint8_t *profileBytes = (uint8_t *)profileData.bytes;
  885. for (int i = 0; i < profileData.length; i++) {
  886. uint8_t currentByte = profileBytes[i];
  887. if (!currentByte || currentByte > 127) {
  888. profileBytes[i] = '.';
  889. }
  890. }
  891. NSString *embeddedProfile = [[NSString alloc] initWithBytesNoCopy:profileBytes
  892. length:profileData.length
  893. encoding:NSASCIIStringEncoding
  894. freeWhenDone:NO];
  895. if (error || !embeddedProfile.length) {
  896. NSString *errorString =
  897. [NSString stringWithFormat:@"Error while reading embedded mobileprovision %@", error];
  898. [self logAPNSConfigurationError:errorString];
  899. return defaultAppTypeProd;
  900. }
  901. NSScanner *scanner = [NSScanner scannerWithString:embeddedProfile];
  902. NSString *plistContents;
  903. if ([scanner scanUpToString:@"<plist" intoString:nil]) {
  904. if ([scanner scanUpToString:@"</plist>" intoString:&plistContents]) {
  905. plistContents = [plistContents stringByAppendingString:@"</plist>"];
  906. }
  907. }
  908. if (!plistContents.length) {
  909. return defaultAppTypeProd;
  910. }
  911. NSData *data = [plistContents dataUsingEncoding:NSUTF8StringEncoding];
  912. if (!data.length) {
  913. [self logAPNSConfigurationError:@"Couldn't read plist fetched from embedded mobileprovision"];
  914. return defaultAppTypeProd;
  915. }
  916. NSError *plistMapError;
  917. id plistData = [NSPropertyListSerialization propertyListWithData:data
  918. options:NSPropertyListImmutable
  919. format:nil
  920. error:&plistMapError];
  921. if (plistMapError || ![plistData isKindOfClass:[NSDictionary class]]) {
  922. NSString *errorString =
  923. [NSString stringWithFormat:@"Error while converting assumed plist to dict %@",
  924. plistMapError.localizedDescription];
  925. [self logAPNSConfigurationError:errorString];
  926. return defaultAppTypeProd;
  927. }
  928. NSDictionary *plistMap = (NSDictionary *)plistData;
  929. if ([plistMap valueForKeyPath:@"ProvisionedDevices"]) {
  930. FIRInstanceIDLoggerDebug(kFIRInstanceIDMessageCodeInstanceID012,
  931. @"Provisioning profile has specifically provisioned devices, "
  932. @"most likely a Dev profile.");
  933. }
  934. NSString *apsEnvironment = [plistMap valueForKeyPath:kEntitlementsAPSEnvironmentKey];
  935. NSString *debugString __unused =
  936. [NSString stringWithFormat:@"APNS Environment in profile: %@", apsEnvironment];
  937. FIRInstanceIDLoggerDebug(kFIRInstanceIDMessageCodeInstanceID013, @"%@", debugString);
  938. // No aps-environment in the profile.
  939. if (!apsEnvironment.length) {
  940. [self logAPNSConfigurationError:@"No aps-environment set. If testing on a device APNS is not "
  941. @"correctly configured. Please recheck your provisioning "
  942. @"profiles. If testing on a simulator this is fine since APNS "
  943. @"doesn't work on the simulator."];
  944. return defaultAppTypeProd;
  945. }
  946. if ([apsEnvironment isEqualToString:kAPSEnvironmentDevelopmentValue]) {
  947. return NO;
  948. }
  949. return defaultAppTypeProd;
  950. }
  951. /// Log error messages only when Messaging exists in the pod.
  952. - (void)logAPNSConfigurationError:(NSString *)errorString {
  953. BOOL hasFirebaseMessaging = NSClassFromString(kFIRInstanceIDFCMSDKClassString) != nil;
  954. if (hasFirebaseMessaging) {
  955. FIRInstanceIDLoggerError(kFIRInstanceIDMessageCodeInstanceID014, @"%@", errorString);
  956. } else {
  957. FIRInstanceIDLoggerDebug(kFIRInstanceIDMessageCodeInstanceID015, @"%@", errorString);
  958. }
  959. }
  960. #pragma mark - Sync InstanceID
  961. - (void)updateFirebaseInstallationID {
  962. FIRInstanceID_WEAKIFY(self);
  963. [self.installations
  964. installationIDWithCompletion:^(NSString *_Nullable installationID, NSError *_Nullable error) {
  965. FIRInstanceID_STRONGIFY(self);
  966. self.firebaseInstallationsID = installationID;
  967. }];
  968. }
  969. - (void)installationIDDidChangeNotificationReceived:(NSNotification *)notification {
  970. NSString *installationAppID =
  971. notification.userInfo[kFIRInstallationIDDidChangeNotificationAppNameKey];
  972. if ([installationAppID isKindOfClass:[NSString class]] &&
  973. [installationAppID isEqual:self.firebaseAppID]) {
  974. [self updateFirebaseInstallationID];
  975. }
  976. }
  977. - (void)observeFirebaseInstallationIDChanges {
  978. [[NSNotificationCenter defaultCenter] removeObserver:self
  979. name:FIRInstallationIDDidChangeNotification
  980. object:nil];
  981. [[NSNotificationCenter defaultCenter]
  982. addObserver:self
  983. selector:@selector(installationIDDidChangeNotificationReceived:)
  984. name:FIRInstallationIDDidChangeNotification
  985. object:nil];
  986. }
  987. @end