FIRInstanceID.m 43 KB

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