FIRInstanceID.m 44 KB

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