FIRMessaging.m 42 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041
  1. /*
  2. * Copyright 2017 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. #if !__has_feature(objc_arc)
  17. #error FIRMessagingLib should be compiled with ARC.
  18. #endif
  19. #import "FirebaseMessaging/Sources/Public/FirebaseMessaging/FIRMessaging.h"
  20. #import <GoogleUtilities/GULAppDelegateSwizzler.h>
  21. #import <GoogleUtilities/GULAppEnvironmentUtil.h>
  22. #import <GoogleUtilities/GULReachabilityChecker.h>
  23. #import <GoogleUtilities/GULUserDefaults.h>
  24. #import "FirebaseCore/Extension/FirebaseCoreInternal.h"
  25. #import "FirebaseInstallations/Source/Library/Private/FirebaseInstallationsInternal.h"
  26. #import "FirebaseMessaging/Interop/FIRMessagingInterop.h"
  27. #import "FirebaseMessaging/Sources/FIRMessagingAnalytics.h"
  28. #import "FirebaseMessaging/Sources/FIRMessagingCode.h"
  29. #import "FirebaseMessaging/Sources/FIRMessagingConstants.h"
  30. #import "FirebaseMessaging/Sources/FIRMessagingContextManagerService.h"
  31. #import "FirebaseMessaging/Sources/FIRMessagingDefines.h"
  32. #import "FirebaseMessaging/Sources/FIRMessagingLogger.h"
  33. #import "FirebaseMessaging/Sources/FIRMessagingPubSub.h"
  34. #import "FirebaseMessaging/Sources/FIRMessagingRemoteNotificationsProxy.h"
  35. #import "FirebaseMessaging/Sources/FIRMessagingRmqManager.h"
  36. #import "FirebaseMessaging/Sources/FIRMessagingSyncMessageManager.h"
  37. #import "FirebaseMessaging/Sources/FIRMessagingUtilities.h"
  38. #import "FirebaseMessaging/Sources/FIRMessaging_Private.h"
  39. #import "FirebaseMessaging/Sources/NSError+FIRMessaging.h"
  40. #import "FirebaseMessaging/Sources/Token/FIRMessagingAuthService.h"
  41. #import "FirebaseMessaging/Sources/Token/FIRMessagingTokenInfo.h"
  42. #import "FirebaseMessaging/Sources/Token/FIRMessagingTokenManager.h"
  43. #import "Interop/Analytics/Public/FIRAnalyticsInterop.h"
  44. static NSString *const kFIRMessagingMessageViaAPNSRootKey = @"aps";
  45. static NSString *const kFIRMessagingReachabilityHostname = @"www.google.com";
  46. const NSNotificationName FIRMessagingRegistrationTokenRefreshedNotification =
  47. @"com.firebase.messaging.notif.fcm-token-refreshed";
  48. NSString *const kFIRMessagingUserDefaultsKeyAutoInitEnabled =
  49. @"com.firebase.messaging.auto-init.enabled"; // Auto Init Enabled key stored in NSUserDefaults
  50. NSString *const kFIRMessagingPlistAutoInitEnabled =
  51. @"FirebaseMessagingAutoInitEnabled"; // Auto Init Enabled key stored in Info.plist
  52. NSString *const FIRMessagingErrorDomain = @"com.google.fcm";
  53. BOOL FIRMessagingIsAPNSSyncMessage(NSDictionary *message) {
  54. if ([message[kFIRMessagingMessageViaAPNSRootKey] isKindOfClass:[NSDictionary class]]) {
  55. NSDictionary *aps = message[kFIRMessagingMessageViaAPNSRootKey];
  56. if (aps && [aps isKindOfClass:[NSDictionary class]]) {
  57. return [aps[kFIRMessagingMessageAPNSContentAvailableKey] boolValue];
  58. }
  59. }
  60. return NO;
  61. }
  62. BOOL FIRMessagingIsContextManagerMessage(NSDictionary *message) {
  63. return [FIRMessagingContextManagerService isContextManagerMessage:message];
  64. }
  65. @interface FIRMessagingMessageInfo ()
  66. @property(nonatomic, readwrite, assign) FIRMessagingMessageStatus status;
  67. @end
  68. @implementation FIRMessagingMessageInfo
  69. - (instancetype)init {
  70. FIRMessagingInvalidateInitializer();
  71. }
  72. - (instancetype)initWithStatus:(FIRMessagingMessageStatus)status {
  73. self = [super init];
  74. if (self) {
  75. _status = status;
  76. }
  77. return self;
  78. }
  79. @end
  80. @interface FIRMessaging () <GULReachabilityDelegate>
  81. // FIRApp properties
  82. @property(nonatomic, readwrite, strong) NSData *apnsTokenData;
  83. @property(nonatomic, readwrite, strong) FIRMessagingClient *client;
  84. @property(nonatomic, readwrite, strong) GULReachabilityChecker *reachability;
  85. @property(nonatomic, readwrite, strong) FIRMessagingPubSub *pubsub;
  86. @property(nonatomic, readwrite, strong) FIRMessagingRmqManager *rmq2Manager;
  87. @property(nonatomic, readwrite, strong) FIRMessagingSyncMessageManager *syncMessageManager;
  88. @property(nonatomic, readwrite, strong) GULUserDefaults *messagingUserDefaults;
  89. @property(nonatomic, readwrite, strong) FIRInstallations *installations;
  90. @property(nonatomic, readwrite, strong) FIRMessagingTokenManager *tokenManager;
  91. @property(nonatomic, readwrite, strong) FIRHeartbeatLogger *heartbeatLogger;
  92. /// Message ID's logged for analytics. This prevents us from logging the same message twice
  93. /// which can happen if the user inadvertently calls `appDidReceiveMessage` along with us
  94. /// calling it implicitly during swizzling.
  95. @property(nonatomic, readwrite, strong) NSMutableSet *loggedMessageIDs;
  96. @property(nonatomic, readwrite, strong) id<FIRAnalyticsInterop> _Nullable analytics;
  97. @end
  98. @interface FIRMessaging () <FIRMessagingInterop, FIRLibrary>
  99. @end
  100. @implementation FIRMessaging
  101. + (FIRMessaging *)messaging {
  102. FIRApp *defaultApp = [FIRApp defaultApp]; // Missing configure will be logged here.
  103. id<FIRMessagingInterop> instance = FIR_COMPONENT(FIRMessagingInterop, defaultApp.container);
  104. // We know the instance coming from the container is a FIRMessaging instance, cast it and move on.
  105. return (FIRMessaging *)instance;
  106. }
  107. - (instancetype)initWithAnalytics:(nullable id<FIRAnalyticsInterop>)analytics
  108. userDefaults:(GULUserDefaults *)defaults
  109. heartbeatLogger:(FIRHeartbeatLogger *)heartbeatLogger {
  110. self = [super init];
  111. if (self != nil) {
  112. _loggedMessageIDs = [NSMutableSet set];
  113. _messagingUserDefaults = defaults;
  114. _analytics = analytics;
  115. _heartbeatLogger = heartbeatLogger;
  116. }
  117. return self;
  118. }
  119. - (void)dealloc {
  120. [self.reachability stop];
  121. [[NSNotificationCenter defaultCenter] removeObserver:self];
  122. [self teardown];
  123. }
  124. #pragma mark - Config
  125. + (void)load {
  126. [FIRApp registerInternalLibrary:(Class<FIRLibrary>)self withName:@"fire-fcm"];
  127. }
  128. + (nonnull NSArray<FIRComponent *> *)componentsToRegister {
  129. FIRComponentCreationBlock creationBlock =
  130. ^id _Nullable(FIRComponentContainer *container, BOOL *isCacheable) {
  131. if (!container.app.isDefaultApp) {
  132. // Only start for the default FIRApp.
  133. FIRMessagingLoggerDebug(kFIRMessagingMessageCodeFIRApp001,
  134. @"Firebase Messaging only works with the default app.");
  135. return nil;
  136. }
  137. // Ensure it's cached so it returns the same instance every time messaging is called.
  138. *isCacheable = YES;
  139. id<FIRAnalyticsInterop> analytics = FIR_COMPONENT(FIRAnalyticsInterop, container);
  140. FIRMessaging *messaging =
  141. [[FIRMessaging alloc] initWithAnalytics:analytics
  142. userDefaults:[GULUserDefaults standardUserDefaults]
  143. heartbeatLogger:container.app.heartbeatLogger];
  144. [messaging start];
  145. [messaging configureMessagingWithOptions:container.app.options];
  146. [messaging configureNotificationSwizzlingIfEnabled];
  147. return messaging;
  148. };
  149. FIRComponent *messagingProvider =
  150. [FIRComponent componentWithProtocol:@protocol(FIRMessagingInterop)
  151. instantiationTiming:FIRInstantiationTimingEagerInDefaultApp
  152. creationBlock:creationBlock];
  153. return @[ messagingProvider ];
  154. }
  155. - (void)configureMessagingWithOptions:(FIROptions *)options {
  156. NSString *GCMSenderID = options.GCMSenderID;
  157. if (!GCMSenderID.length) {
  158. FIRMessagingLoggerError(kFIRMessagingMessageCodeFIRApp000,
  159. @"Firebase not set up correctly, nil or empty senderID.");
  160. [NSException raise:FIRMessagingErrorDomain
  161. format:@"Could not configure Firebase Messaging. GCMSenderID must not be nil or "
  162. @"empty."];
  163. }
  164. self.tokenManager.fcmSenderID = GCMSenderID;
  165. self.tokenManager.firebaseAppID = options.googleAppID;
  166. // FCM generates a FCM token during app start for sending push notification to device.
  167. // This is not needed for app extension except for watch.
  168. #if TARGET_OS_WATCH
  169. [self didCompleteConfigure];
  170. #else // TARGET_OS_WATCH
  171. if (![GULAppEnvironmentUtil isAppExtension]) {
  172. [self didCompleteConfigure];
  173. }
  174. #endif // TARGET_OS_WATCH
  175. }
  176. - (void)didCompleteConfigure {
  177. NSString *cachedToken =
  178. [self.tokenManager cachedTokenInfoWithAuthorizedEntity:self.tokenManager.fcmSenderID
  179. scope:kFIRMessagingDefaultTokenScope]
  180. .token;
  181. // When there is a cached token, do the token refresh.
  182. // Before fetching FCM token, confirm there is an APNS token to avoid validation error
  183. // This error is innocuous since we refetch after APNS token is set but it can seem alarming
  184. if (cachedToken) {
  185. // Clean up expired tokens by checking the token refresh policy.
  186. [self.installations installationIDWithCompletion:^(NSString *_Nullable identifier,
  187. NSError *_Nullable error) {
  188. if ([self.tokenManager checkTokenRefreshPolicyWithIID:identifier] && self.APNSToken) {
  189. // Default token is expired, fetch default token from server.
  190. [self retrieveFCMTokenForSenderID:self.tokenManager.fcmSenderID
  191. completion:^(NSString *_Nullable FCMToken, NSError *_Nullable error){
  192. }];
  193. }
  194. // Set the default FCM token, there's an issue that FIRApp configure
  195. // happens before developers able to set the delegate
  196. // Hence first token set must be happen here after listener is set
  197. // TODO(chliangGoogle) Need to investigate better solution.
  198. [self updateDefaultFCMToken:self.FCMToken];
  199. }];
  200. } else if (self.isAutoInitEnabled && self.APNSToken) {
  201. // When there is no cached token, must check auto init is enabled.
  202. // If it's disabled, don't initiate token generation/refresh.
  203. // If no cache token and auto init is enabled, fetch a token from server.
  204. [self retrieveFCMTokenForSenderID:self.tokenManager.fcmSenderID
  205. completion:^(NSString *_Nullable FCMToken, NSError *_Nullable error){
  206. }];
  207. }
  208. }
  209. - (void)configureNotificationSwizzlingIfEnabled {
  210. // Swizzle remote-notification-related methods (app delegate and UNUserNotificationCenter)
  211. if ([FIRMessagingRemoteNotificationsProxy canSwizzleMethods]) {
  212. NSString *docsURLString = @"https://firebase.google.com/docs/cloud-messaging/ios/client"
  213. @"#method_swizzling_in_firebase_messaging";
  214. FIRMessagingLoggerNotice(kFIRMessagingMessageCodeFIRApp000,
  215. @"FIRMessaging Remote Notifications proxy enabled, will swizzle "
  216. @"remote notification receiver handlers. If you'd prefer to manually "
  217. @"integrate Firebase Messaging, add \"%@\" to your Info.plist, "
  218. @"and set it to NO. Follow the instructions at:\n%@\nto ensure "
  219. @"proper integration.",
  220. kFIRMessagingRemoteNotificationsProxyEnabledInfoPlistKey,
  221. docsURLString);
  222. [[FIRMessagingRemoteNotificationsProxy sharedProxy] swizzleMethodsIfPossible];
  223. }
  224. }
  225. - (void)start {
  226. [self setupFileManagerSubDirectory];
  227. [self setupNotificationListeners];
  228. self.tokenManager =
  229. [[FIRMessagingTokenManager alloc] initWithHeartbeatLogger:self.heartbeatLogger];
  230. self.installations = [FIRInstallations installations];
  231. [self setupTopics];
  232. // Print the library version for logging.
  233. NSString *currentLibraryVersion = FIRFirebaseVersion();
  234. FIRMessagingLoggerInfo(kFIRMessagingMessageCodeMessagingPrintLibraryVersion,
  235. @"FIRMessaging library version %@", currentLibraryVersion);
  236. NSString *hostname = kFIRMessagingReachabilityHostname;
  237. self.reachability = [[GULReachabilityChecker alloc] initWithReachabilityDelegate:self
  238. withHost:hostname];
  239. [self.reachability start];
  240. // setup FIRMessaging objects
  241. [self setupRmqManager];
  242. [self setupSyncMessageManager];
  243. }
  244. - (void)setupFileManagerSubDirectory {
  245. if (![[self class] hasSubDirectory:kFIRMessagingSubDirectoryName]) {
  246. [[self class] createSubDirectory:kFIRMessagingSubDirectoryName];
  247. }
  248. if (![[self class] hasSubDirectory:kFIRMessagingInstanceIDSubDirectoryName]) {
  249. [[self class] createSubDirectory:kFIRMessagingInstanceIDSubDirectoryName];
  250. }
  251. }
  252. - (void)setupNotificationListeners {
  253. // To prevent multiple notifications remove self as observer for all events.
  254. NSNotificationCenter *center = [NSNotificationCenter defaultCenter];
  255. [center removeObserver:self];
  256. [center addObserver:self
  257. selector:@selector(defaultFCMTokenWasRefreshed:)
  258. name:kFIRMessagingRegistrationTokenRefreshNotification
  259. object:nil];
  260. }
  261. - (void)setupRmqManager {
  262. self.rmq2Manager = [[FIRMessagingRmqManager alloc] initWithDatabaseName:@"rmq2"];
  263. [self.rmq2Manager loadRmqId];
  264. }
  265. - (void)setupTopics {
  266. self.pubsub = [[FIRMessagingPubSub alloc] initWithTokenManager:self.tokenManager];
  267. }
  268. - (void)setupSyncMessageManager {
  269. self.syncMessageManager =
  270. [[FIRMessagingSyncMessageManager alloc] initWithRmqManager:self.rmq2Manager];
  271. [self.syncMessageManager removeExpiredSyncMessages];
  272. }
  273. - (void)teardown {
  274. self.pubsub = nil;
  275. self.syncMessageManager = nil;
  276. self.rmq2Manager = nil;
  277. FIRMessagingLoggerDebug(kFIRMessagingMessageCodeMessaging001, @"Did successfully teardown");
  278. }
  279. #pragma mark - Messages
  280. - (FIRMessagingMessageInfo *)appDidReceiveMessage:(NSDictionary *)message {
  281. if (!message.count) {
  282. return [[FIRMessagingMessageInfo alloc] initWithStatus:FIRMessagingMessageStatusUnknown];
  283. }
  284. // For downstream messages that go via MCS we should strip out this key before sending
  285. // the message to the device.
  286. BOOL isOldMessage = NO;
  287. NSString *messageID = message[kFIRMessagingMessageIDKey];
  288. if (messageID.length) {
  289. [self.rmq2Manager saveS2dMessageWithRmqId:messageID];
  290. BOOL isSyncMessage = FIRMessagingIsAPNSSyncMessage(message);
  291. if (isSyncMessage) {
  292. isOldMessage = [self.syncMessageManager didReceiveAPNSSyncMessage:message];
  293. }
  294. // Prevent duplicates by keeping a cache of all the logged messages during each session.
  295. // The duplicates only happen when the 3P app calls `appDidReceiveMessage:` along with
  296. // us swizzling their implementation to call the same method implicitly.
  297. // We need to rule out the contextual message because it shares the same message ID
  298. // as the local notification it will schedule. And because it is also a APNSSync message
  299. // its duplication is already checked previously.
  300. if (!isOldMessage && !FIRMessagingIsContextManagerMessage(message)) {
  301. isOldMessage = [self.loggedMessageIDs containsObject:messageID];
  302. if (!isOldMessage) {
  303. [self.loggedMessageIDs addObject:messageID];
  304. }
  305. }
  306. }
  307. if (!isOldMessage) {
  308. [FIRMessagingAnalytics logMessage:message toAnalytics:_analytics];
  309. [self handleContextManagerMessage:message];
  310. [self handleIncomingLinkIfNeededFromMessage:message];
  311. }
  312. return [[FIRMessagingMessageInfo alloc] initWithStatus:FIRMessagingMessageStatusNew];
  313. }
  314. - (BOOL)handleContextManagerMessage:(NSDictionary *)message {
  315. if (FIRMessagingIsContextManagerMessage(message)) {
  316. return [FIRMessagingContextManagerService handleContextManagerMessage:message];
  317. }
  318. return NO;
  319. }
  320. - (void)handleIncomingLinkIfNeededFromMessage:(NSDictionary *)message {
  321. #if TARGET_OS_IOS || TARGET_OS_TV || TARGET_OS_VISION
  322. NSURL *url = [self linkURLFromMessage:message];
  323. if (url == nil) {
  324. return;
  325. }
  326. if (![NSThread isMainThread]) {
  327. dispatch_async(dispatch_get_main_queue(), ^{
  328. [self handleIncomingLinkIfNeededFromMessage:message];
  329. });
  330. return;
  331. }
  332. UIApplication *application = [GULAppDelegateSwizzler sharedApplication];
  333. if (!application) {
  334. return;
  335. }
  336. id<UIApplicationDelegate> appDelegate = application.delegate;
  337. SEL continueUserActivitySelector = @selector(application:
  338. continueUserActivity:restorationHandler:);
  339. // Due to FIRAAppDelegateProxy swizzling, this selector will most likely get chosen, whether or
  340. // not the actual application has implemented
  341. // |application:continueUserActivity:restorationHandler:|. A warning will be displayed to the user
  342. // if they haven't implemented it.
  343. if ([NSUserActivity class] != nil &&
  344. [appDelegate respondsToSelector:continueUserActivitySelector]) {
  345. // Use string literal to ensure compatibility with Xcode 26 and iOS 18
  346. NSString *browsingWebType = @"NSUserActivityTypeBrowsingWeb";
  347. NSUserActivity *userActivity = [[NSUserActivity alloc] initWithActivityType:browsingWebType];
  348. userActivity.webpageURL = url;
  349. [appDelegate application:application
  350. continueUserActivity:userActivity
  351. restorationHandler:^(NSArray *_Nullable restorableObjects){
  352. // Do nothing, as we don't support the app calling this block
  353. }];
  354. }
  355. #endif // TARGET_OS_IOS || TARGET_OS_TV || TARGET_OS_VISION
  356. }
  357. - (NSURL *)linkURLFromMessage:(NSDictionary *)message {
  358. NSString *urlString = message[kFIRMessagingMessageLinkKey];
  359. if (urlString == nil || ![urlString isKindOfClass:[NSString class]] || urlString.length == 0) {
  360. return nil;
  361. }
  362. NSURL *url = [NSURL URLWithString:urlString];
  363. return url;
  364. }
  365. #pragma mark - APNS
  366. - (NSData *)APNSToken {
  367. return self.apnsTokenData;
  368. }
  369. - (void)setAPNSToken:(NSData *)APNSToken {
  370. [self setAPNSToken:APNSToken type:FIRMessagingAPNSTokenTypeUnknown];
  371. }
  372. - (void)setAPNSToken:(NSData *)apnsToken type:(FIRMessagingAPNSTokenType)type {
  373. if ([apnsToken isEqual:self.apnsTokenData]) {
  374. return;
  375. }
  376. self.apnsTokenData = apnsToken;
  377. // Notify InstanceID that APNS Token has been set.
  378. NSDictionary *userInfo = @{kFIRMessagingAPNSTokenType : @(type)};
  379. // TODO(chliang) This is sent to InstanceID in case users are still using the deprecated SDK.
  380. // Should be safe to remove once InstanceID is removed.
  381. NSNotification *notification =
  382. [NSNotification notificationWithName:kFIRMessagingAPNSTokenNotification
  383. object:[apnsToken copy]
  384. userInfo:userInfo];
  385. [[NSNotificationQueue defaultQueue] enqueueNotification:notification postingStyle:NSPostASAP];
  386. [self.tokenManager setAPNSToken:[apnsToken copy] withUserInfo:userInfo];
  387. }
  388. #pragma mark - FCM Token
  389. - (BOOL)isAutoInitEnabled {
  390. // Defer to the class method since we're just reading from regular userDefaults and we need to
  391. // read this from IID without instantiating the Messaging singleton.
  392. return [[self class] isAutoInitEnabledWithUserDefaults:_messagingUserDefaults];
  393. }
  394. /// Checks if Messaging auto-init is enabled in the user defaults instance passed in. This is
  395. /// exposed as a class property for IID to fetch the property without instantiating an instance of
  396. /// Messaging. Since Messaging can only be used with the default FIRApp, we can have one point of
  397. /// entry without context of which FIRApp instance is being used.
  398. /// ** THIS METHOD IS DEPENDED ON INTERNALLY BY IID USING REFLECTION. PLEASE DO NOT CHANGE THE
  399. /// SIGNATURE, AS IT WOULD BREAK AUTOINIT FUNCTIONALITY WITHIN IID. **
  400. + (BOOL)isAutoInitEnabledWithUserDefaults:(GULUserDefaults *)userDefaults {
  401. // Check storage
  402. id isAutoInitEnabledObject =
  403. [userDefaults objectForKey:kFIRMessagingUserDefaultsKeyAutoInitEnabled];
  404. if (isAutoInitEnabledObject) {
  405. return [isAutoInitEnabledObject boolValue];
  406. }
  407. // Check Info.plist
  408. isAutoInitEnabledObject =
  409. [[NSBundle mainBundle] objectForInfoDictionaryKey:kFIRMessagingPlistAutoInitEnabled];
  410. if (isAutoInitEnabledObject) {
  411. return [isAutoInitEnabledObject boolValue];
  412. }
  413. // If none of above exists, we default to the global switch that comes from FIRApp.
  414. return [[FIRApp defaultApp] isDataCollectionDefaultEnabled];
  415. }
  416. - (void)setAutoInitEnabled:(BOOL)autoInitEnabled {
  417. BOOL isFCMAutoInitEnabled = [self isAutoInitEnabled];
  418. [_messagingUserDefaults setBool:autoInitEnabled
  419. forKey:kFIRMessagingUserDefaultsKeyAutoInitEnabled];
  420. if (!isFCMAutoInitEnabled && autoInitEnabled) {
  421. [self.tokenManager tokenAndRequestIfNotExist];
  422. }
  423. }
  424. - (NSString *)FCMToken {
  425. // Gets the current default token, and requests a new one if it doesn't exist.
  426. NSString *token = [self.tokenManager tokenAndRequestIfNotExist];
  427. return token;
  428. }
  429. - (void)tokenWithCompletion:(FIRMessagingFCMTokenFetchCompletion)completion {
  430. FIROptions *options = FIRApp.defaultApp.options;
  431. [self retrieveFCMTokenForSenderID:options.GCMSenderID completion:completion];
  432. }
  433. - (void)deleteTokenWithCompletion:(FIRMessagingDeleteFCMTokenCompletion)completion {
  434. FIROptions *options = FIRApp.defaultApp.options;
  435. [self deleteFCMTokenForSenderID:options.GCMSenderID completion:completion];
  436. }
  437. - (void)retrieveFCMTokenForSenderID:(nonnull NSString *)senderID
  438. completion:(nonnull FIRMessagingFCMTokenFetchCompletion)completion {
  439. if (!senderID.length) {
  440. NSString *description = @"Couldn't fetch token because a Sender ID was not supplied. A valid "
  441. @"Sender ID is required to fetch an FCM token";
  442. FIRMessagingLoggerError(kFIRMessagingMessageCodeSenderIDNotSuppliedForTokenFetch, @"%@",
  443. description);
  444. if (completion) {
  445. NSError *error = [NSError messagingErrorWithCode:kFIRMessagingErrorCodeMissingAuthorizedEntity
  446. failureReason:description];
  447. completion(nil, error);
  448. }
  449. return;
  450. }
  451. NSDictionary *options = nil;
  452. if (self.APNSToken) {
  453. options = @{kFIRMessagingTokenOptionsAPNSKey : self.APNSToken};
  454. } else {
  455. FIRMessagingLoggerWarn(kFIRMessagingMessageCodeAPNSTokenNotAvailableDuringTokenFetch,
  456. @"APNS device token not set before retrieving FCM Token for Sender ID "
  457. @"'%@'."
  458. @"Be sure to re-retrieve the FCM token once the APNS device token is "
  459. @"set.",
  460. senderID);
  461. }
  462. [self.tokenManager
  463. tokenWithAuthorizedEntity:senderID
  464. scope:kFIRMessagingDefaultTokenScope
  465. options:options
  466. handler:^(NSString *_Nullable FCMToken, NSError *_Nullable error) {
  467. if (completion) {
  468. completion(FCMToken, error);
  469. }
  470. }];
  471. }
  472. - (void)deleteFCMTokenForSenderID:(nonnull NSString *)senderID
  473. completion:(nonnull FIRMessagingDeleteFCMTokenCompletion)completion {
  474. if (!senderID.length) {
  475. NSString *description = @"Couldn't delete token because a Sender ID was not supplied. A "
  476. @"valid Sender ID is required to delete an FCM token";
  477. FIRMessagingLoggerError(kFIRMessagingMessageCodeSenderIDNotSuppliedForTokenDelete, @"%@",
  478. description);
  479. if (completion) {
  480. NSError *error = [NSError messagingErrorWithCode:kFIRMessagingErrorCodeInvalidRequest
  481. failureReason:description];
  482. completion(error);
  483. }
  484. return;
  485. }
  486. FIRMessaging_WEAKIFY(self);
  487. [self.installations
  488. installationIDWithCompletion:^(NSString *_Nullable identifier, NSError *_Nullable error) {
  489. FIRMessaging_STRONGIFY(self);
  490. if (error) {
  491. NSError *newError = [NSError messagingErrorWithCode:kFIRMessagingErrorCodeInvalidIdentity
  492. failureReason:@"Failed to get installation ID."];
  493. completion(newError);
  494. } else {
  495. [self.tokenManager deleteTokenWithAuthorizedEntity:senderID
  496. scope:kFIRMessagingDefaultTokenScope
  497. instanceID:identifier
  498. handler:^(NSError *_Nullable error) {
  499. if (completion) {
  500. completion(error);
  501. }
  502. }];
  503. }
  504. }];
  505. }
  506. - (void)deleteDataWithCompletion:(void (^)(NSError *_Nullable))completion {
  507. FIRMessaging_WEAKIFY(self);
  508. [self.tokenManager deleteWithHandler:^(NSError *error) {
  509. FIRMessaging_STRONGIFY(self);
  510. if (error) {
  511. if (completion) {
  512. completion(error);
  513. }
  514. return;
  515. }
  516. // Only request new token if FCM auto initialization is
  517. // enabled.
  518. if ([self isAutoInitEnabled]) {
  519. // Deletion succeeds! Requesting new checkin, IID and token.
  520. [self tokenWithCompletion:^(NSString *_Nullable token, NSError *_Nullable error) {
  521. if (completion) {
  522. completion(error);
  523. }
  524. }];
  525. return;
  526. }
  527. if (completion) {
  528. completion(nil);
  529. }
  530. }];
  531. }
  532. #pragma mark - FIRMessagingDelegate helper methods
  533. - (void)setDelegate:(id<FIRMessagingDelegate>)delegate {
  534. _delegate = delegate;
  535. [self validateDelegateConformsToTokenAvailabilityMethods];
  536. }
  537. // Check if the delegate conforms to |didReceiveRegistrationToken:|
  538. // and display a warning to the developer if not.
  539. // NOTE: Once |didReceiveRegistrationToken:| can be made a required method, this
  540. // check can be removed.
  541. - (void)validateDelegateConformsToTokenAvailabilityMethods {
  542. if (self.delegate && ![self.delegate respondsToSelector:@selector(messaging:
  543. didReceiveRegistrationToken:)]) {
  544. FIRMessagingLoggerWarn(kFIRMessagingMessageCodeTokenDelegateMethodsNotImplemented,
  545. @"The object %@ does not respond to "
  546. @"-messaging:didReceiveRegistrationToken:. Please implement "
  547. @"-messaging:didReceiveRegistrationToken: to be provided with an FCM "
  548. @"token.",
  549. self.delegate.description);
  550. }
  551. }
  552. - (void)notifyRefreshedFCMToken {
  553. __weak FIRMessaging *weakSelf = self;
  554. if (![NSThread isMainThread]) {
  555. dispatch_async(dispatch_get_main_queue(), ^{
  556. [weakSelf notifyRefreshedFCMToken];
  557. });
  558. return;
  559. }
  560. if ([self.delegate respondsToSelector:@selector(messaging:didReceiveRegistrationToken:)]) {
  561. [self.delegate messaging:self didReceiveRegistrationToken:self.tokenManager.defaultFCMToken];
  562. }
  563. // Should always trigger the token refresh notification when the delegate method is called
  564. NSNotificationCenter *center = [NSNotificationCenter defaultCenter];
  565. [center postNotificationName:FIRMessagingRegistrationTokenRefreshedNotification
  566. object:self.tokenManager.defaultFCMToken];
  567. }
  568. #pragma mark - Topics
  569. + (NSString *)normalizeTopic:(NSString *)topic {
  570. if (!topic.length) {
  571. return nil;
  572. }
  573. if (![FIRMessagingPubSub hasTopicsPrefix:topic]) {
  574. topic = [FIRMessagingPubSub addPrefixToTopic:topic];
  575. }
  576. if ([FIRMessagingPubSub isValidTopicWithPrefix:topic]) {
  577. return [topic copy];
  578. }
  579. return nil;
  580. }
  581. - (void)subscribeToTopic:(NSString *)topic {
  582. [self subscribeToTopic:topic completion:nil];
  583. }
  584. - (void)subscribeToTopic:(NSString *)topic
  585. completion:(nullable FIRMessagingTopicOperationCompletion)completion {
  586. if ([FIRMessagingPubSub hasTopicsPrefix:topic]) {
  587. FIRMessagingLoggerWarn(kFIRMessagingMessageCodeTopicFormatIsDeprecated,
  588. @"Format '%@' is deprecated. Only '%@' should be used in "
  589. @"subscribeToTopic.",
  590. topic, [FIRMessagingPubSub removePrefixFromTopic:topic]);
  591. }
  592. __weak FIRMessaging *weakSelf = self;
  593. [self
  594. retrieveFCMTokenForSenderID:self.tokenManager.fcmSenderID
  595. completion:^(NSString *_Nullable FCMToken, NSError *_Nullable error) {
  596. if (error) {
  597. FIRMessagingLoggerError(kFIRMessagingMessageCodeMessaging010,
  598. @"The subscription operation failed due to an "
  599. @"error getting the FCM token: %@.",
  600. error);
  601. if (completion) {
  602. completion(error);
  603. }
  604. return;
  605. }
  606. FIRMessaging *strongSelf = weakSelf;
  607. NSString *normalizeTopic = [[strongSelf class] normalizeTopic:topic];
  608. if (normalizeTopic.length) {
  609. [strongSelf.pubsub subscribeToTopic:normalizeTopic handler:completion];
  610. return;
  611. }
  612. NSString *failureReason = [NSString
  613. stringWithFormat:@"Cannot parse topic name: '%@'. Will not subscribe.",
  614. topic];
  615. FIRMessagingLoggerError(kFIRMessagingMessageCodeMessaging009, @"%@",
  616. failureReason);
  617. if (completion) {
  618. completion([NSError
  619. messagingErrorWithCode:kFIRMessagingErrorCodeInvalidTopicName
  620. failureReason:failureReason]);
  621. }
  622. }];
  623. }
  624. - (void)unsubscribeFromTopic:(NSString *)topic {
  625. [self unsubscribeFromTopic:topic completion:nil];
  626. }
  627. - (void)unsubscribeFromTopic:(NSString *)topic
  628. completion:(nullable FIRMessagingTopicOperationCompletion)completion {
  629. if ([FIRMessagingPubSub hasTopicsPrefix:topic]) {
  630. FIRMessagingLoggerWarn(kFIRMessagingMessageCodeTopicFormatIsDeprecated,
  631. @"Format '%@' is deprecated. Only '%@' should be used in "
  632. @"unsubscribeFromTopic.",
  633. topic, [FIRMessagingPubSub removePrefixFromTopic:topic]);
  634. }
  635. __weak FIRMessaging *weakSelf = self;
  636. [self retrieveFCMTokenForSenderID:self.tokenManager.fcmSenderID
  637. completion:^(NSString *_Nullable FCMToken, NSError *_Nullable error) {
  638. if (error) {
  639. FIRMessagingLoggerError(kFIRMessagingMessageCodeMessaging012,
  640. @"The unsubscription operation failed due to "
  641. @"an error getting the FCM token: %@.",
  642. error);
  643. if (completion) {
  644. completion(error);
  645. }
  646. return;
  647. }
  648. FIRMessaging *strongSelf = weakSelf;
  649. NSString *normalizeTopic = [[strongSelf class] normalizeTopic:topic];
  650. if (normalizeTopic.length) {
  651. [strongSelf.pubsub unsubscribeFromTopic:normalizeTopic
  652. handler:completion];
  653. return;
  654. }
  655. NSString *failureReason = [NSString
  656. stringWithFormat:
  657. @"Cannot parse topic name: '%@'. Will not unsubscribe.", topic];
  658. FIRMessagingLoggerError(kFIRMessagingMessageCodeMessaging011, @"%@",
  659. failureReason);
  660. if (completion) {
  661. completion([NSError
  662. messagingErrorWithCode:kFIRMessagingErrorCodeInvalidTopicName
  663. failureReason:failureReason]);
  664. }
  665. }];
  666. }
  667. #pragma mark - GULReachabilityDelegate
  668. - (void)reachability:(GULReachabilityChecker *)reachability
  669. statusChanged:(GULReachabilityStatus)status {
  670. [self onNetworkStatusChanged];
  671. }
  672. #pragma mark - Network
  673. - (void)onNetworkStatusChanged {
  674. if ([self isNetworkAvailable]) {
  675. [self.pubsub scheduleSync:YES];
  676. }
  677. }
  678. - (BOOL)isNetworkAvailable {
  679. GULReachabilityStatus status = self.reachability.reachabilityStatus;
  680. return (status == kGULReachabilityViaCellular || status == kGULReachabilityViaWifi);
  681. }
  682. - (FIRMessagingNetworkStatus)networkType {
  683. GULReachabilityStatus status = self.reachability.reachabilityStatus;
  684. if (![self isNetworkAvailable]) {
  685. return kFIRMessagingReachabilityNotReachable;
  686. } else if (status == kGULReachabilityViaCellular) {
  687. return kFIRMessagingReachabilityReachableViaWWAN;
  688. } else {
  689. return kFIRMessagingReachabilityReachableViaWiFi;
  690. }
  691. }
  692. #pragma mark - Notifications
  693. - (void)defaultFCMTokenWasRefreshed:(NSNotification *)notification {
  694. if (notification.object && ![notification.object isKindOfClass:[NSString class]]) {
  695. FIRMessagingLoggerDebug(kFIRMessagingMessageCodeMessaging015,
  696. @"Invalid default FCM token type %@",
  697. NSStringFromClass([notification.object class]));
  698. return;
  699. }
  700. NSString *newToken = [(NSString *)notification.object copy];
  701. [self updateDefaultFCMToken:newToken];
  702. }
  703. - (void)updateDefaultFCMToken:(NSString *)defaultFCMToken {
  704. NSString *oldToken = self.tokenManager.defaultFCMToken;
  705. NSString *newToken = defaultFCMToken;
  706. if ([self.tokenManager hasTokenChangedFromOldToken:oldToken toNewToken:newToken]) {
  707. // Make sure to set default token first before notifying others.
  708. [self.tokenManager saveDefaultTokenInfoInKeychain:newToken];
  709. [self notifyDelegateOfFCMTokenAvailability];
  710. [self.pubsub scheduleSync:YES];
  711. }
  712. }
  713. - (void)notifyDelegateOfFCMTokenAvailability {
  714. __weak FIRMessaging *weakSelf = self;
  715. if (![NSThread isMainThread]) {
  716. dispatch_async(dispatch_get_main_queue(), ^{
  717. [weakSelf notifyDelegateOfFCMTokenAvailability];
  718. });
  719. return;
  720. }
  721. if ([self.delegate respondsToSelector:@selector(messaging:didReceiveRegistrationToken:)]) {
  722. [self.delegate messaging:self didReceiveRegistrationToken:self.tokenManager.defaultFCMToken];
  723. }
  724. // Should always trigger the token refresh notification when the delegate method is called
  725. NSNotificationCenter *center = [NSNotificationCenter defaultCenter];
  726. [center postNotificationName:FIRMessagingRegistrationTokenRefreshedNotification
  727. object:self.tokenManager.defaultFCMToken];
  728. }
  729. #pragma mark - Application Support Directory
  730. + (BOOL)hasSubDirectory:(NSString *)subDirectoryName {
  731. NSString *subDirectoryPath = [self pathForSubDirectory:subDirectoryName];
  732. BOOL isDirectory;
  733. if (![[NSFileManager defaultManager] fileExistsAtPath:subDirectoryPath
  734. isDirectory:&isDirectory]) {
  735. return NO;
  736. } else if (!isDirectory) {
  737. return NO;
  738. }
  739. return YES;
  740. }
  741. + (NSString *)pathForSubDirectory:(NSString *)subDirectoryName {
  742. NSArray *directoryPaths =
  743. NSSearchPathForDirectoriesInDomains(FIRMessagingSupportedDirectory(), NSUserDomainMask, YES);
  744. NSString *dirPath = directoryPaths.lastObject;
  745. NSArray *components = @[ dirPath, subDirectoryName ];
  746. return [NSString pathWithComponents:components];
  747. }
  748. + (BOOL)createSubDirectory:(NSString *)subDirectoryName {
  749. NSString *subDirectoryPath = [self pathForSubDirectory:subDirectoryName];
  750. BOOL hasSubDirectory;
  751. if (![[NSFileManager defaultManager] fileExistsAtPath:subDirectoryPath
  752. isDirectory:&hasSubDirectory]) {
  753. NSError *error;
  754. [[NSFileManager defaultManager] createDirectoryAtPath:subDirectoryPath
  755. withIntermediateDirectories:YES
  756. attributes:nil
  757. error:&error];
  758. if (error) {
  759. FIRMessagingLoggerError(kFIRMessagingMessageCodeMessaging017,
  760. @"Cannot create directory %@, error: %@", subDirectoryPath, error);
  761. return NO;
  762. }
  763. } else {
  764. if (!hasSubDirectory) {
  765. FIRMessagingLoggerError(kFIRMessagingMessageCodeMessaging018,
  766. @"Found file instead of directory at %@", subDirectoryPath);
  767. return NO;
  768. }
  769. }
  770. return YES;
  771. }
  772. #pragma mark - Locales
  773. + (NSString *)currentLocale {
  774. NSArray *locales = [self firebaseLocales];
  775. NSArray *preferredLocalizations =
  776. [NSBundle preferredLocalizationsFromArray:locales
  777. forPreferences:[NSLocale preferredLanguages]];
  778. NSString *legalDocsLanguage = [preferredLocalizations firstObject];
  779. // Use en as the default language
  780. return legalDocsLanguage ? legalDocsLanguage : @"en";
  781. }
  782. + (NSArray *)firebaseLocales {
  783. NSMutableArray *locales = [NSMutableArray array];
  784. NSDictionary *localesMap = [self firebaselocalesMap];
  785. for (NSString *key in localesMap) {
  786. [locales addObjectsFromArray:localesMap[key]];
  787. }
  788. return locales;
  789. }
  790. + (NSDictionary *)firebaselocalesMap {
  791. return @{
  792. // Albanian
  793. @"sq" : @[ @"sq_AL" ],
  794. // Belarusian
  795. @"be" : @[ @"be_BY" ],
  796. // Bulgarian
  797. @"bg" : @[ @"bg_BG" ],
  798. // Catalan
  799. @"ca" : @[ @"ca", @"ca_ES" ],
  800. // Croatian
  801. @"hr" : @[ @"hr", @"hr_HR" ],
  802. // Czech
  803. @"cs" : @[ @"cs", @"cs_CZ" ],
  804. // Danish
  805. @"da" : @[ @"da", @"da_DK" ],
  806. // Estonian
  807. @"et" : @[ @"et_EE" ],
  808. // Finnish
  809. @"fi" : @[ @"fi", @"fi_FI" ],
  810. // Hebrew
  811. @"he" : @[ @"he", @"iw_IL" ],
  812. // Hindi
  813. @"hi" : @[ @"hi_IN" ],
  814. // Hungarian
  815. @"hu" : @[ @"hu", @"hu_HU" ],
  816. // Icelandic
  817. @"is" : @[ @"is_IS" ],
  818. // Indonesian
  819. @"id" : @[ @"id", @"in_ID", @"id_ID" ],
  820. // Irish
  821. @"ga" : @[ @"ga_IE" ],
  822. // Korean
  823. @"ko" : @[ @"ko", @"ko_KR", @"ko-KR" ],
  824. // Latvian
  825. @"lv" : @[ @"lv_LV" ],
  826. // Lithuanian
  827. @"lt" : @[ @"lt_LT" ],
  828. // Macedonian
  829. @"mk" : @[ @"mk_MK" ],
  830. // Malay
  831. @"ms" : @[ @"ms_MY" ],
  832. // Maltese
  833. @"mt" : @[ @"mt_MT" ],
  834. // Polish
  835. @"pl" : @[ @"pl", @"pl_PL", @"pl-PL" ],
  836. // Romanian
  837. @"ro" : @[ @"ro", @"ro_RO" ],
  838. // Russian
  839. @"ru" : @[ @"ru_RU", @"ru", @"ru_BY", @"ru_KZ", @"ru-RU" ],
  840. // Slovak
  841. @"sk" : @[ @"sk", @"sk_SK" ],
  842. // Slovenian
  843. @"sl" : @[ @"sl_SI" ],
  844. // Swedish
  845. @"sv" : @[ @"sv", @"sv_SE", @"sv-SE" ],
  846. // Turkish
  847. @"tr" : @[ @"tr", @"tr-TR", @"tr_TR" ],
  848. // Ukrainian
  849. @"uk" : @[ @"uk", @"uk_UA" ],
  850. // Vietnamese
  851. @"vi" : @[ @"vi", @"vi_VN" ],
  852. // The following are groups of locales or locales that sub-divide a
  853. // language).
  854. // Arabic
  855. @"ar" : @[
  856. @"ar", @"ar_DZ", @"ar_BH", @"ar_EG", @"ar_IQ", @"ar_JO", @"ar_KW",
  857. @"ar_LB", @"ar_LY", @"ar_MA", @"ar_OM", @"ar_QA", @"ar_SA", @"ar_SD",
  858. @"ar_SY", @"ar_TN", @"ar_AE", @"ar_YE", @"ar_GB", @"ar-IQ", @"ar_US"
  859. ],
  860. // Simplified Chinese
  861. @"zh_Hans" : @[ @"zh_CN", @"zh_SG", @"zh-Hans" ],
  862. // Traditional Chinese
  863. @"zh_Hant" : @[ @"zh_HK", @"zh_TW", @"zh-Hant", @"zh-HK", @"zh-TW" ],
  864. // Dutch
  865. @"nl" : @[ @"nl", @"nl_BE", @"nl_NL", @"nl-NL" ],
  866. // English
  867. @"en" : @[
  868. @"en", @"en_AU", @"en_CA", @"en_IN", @"en_IE", @"en_MT", @"en_NZ", @"en_PH",
  869. @"en_SG", @"en_ZA", @"en_GB", @"en_US", @"en_AE", @"en-AE", @"en_AS", @"en-AU",
  870. @"en_BD", @"en-CA", @"en_EG", @"en_ES", @"en_GB", @"en-GB", @"en_HK", @"en_ID",
  871. @"en-IN", @"en_NG", @"en-PH", @"en_PK", @"en-SG", @"en-US"
  872. ],
  873. // French
  874. @"fr" :
  875. @[ @"fr", @"fr_BE", @"fr_CA", @"fr_FR", @"fr_LU", @"fr_CH", @"fr-CA", @"fr-FR", @"fr_MA" ],
  876. // German
  877. @"de" : @[ @"de", @"de_AT", @"de_DE", @"de_LU", @"de_CH", @"de-DE" ],
  878. // Greek
  879. @"el" : @[ @"el", @"el_CY", @"el_GR" ],
  880. // Italian
  881. @"it" : @[ @"it", @"it_IT", @"it_CH", @"it-IT" ],
  882. // Japanese
  883. @"ja" : @[ @"ja", @"ja_JP", @"ja_JP_JP", @"ja-JP" ],
  884. // Norwegian
  885. @"no" : @[ @"nb", @"no_NO", @"no_NO_NY", @"nb_NO" ],
  886. // Brazilian Portuguese
  887. @"pt_BR" : @[ @"pt_BR", @"pt-BR" ],
  888. // European Portuguese
  889. @"pt_PT" : @[ @"pt", @"pt_PT", @"pt-PT" ],
  890. // Serbian
  891. @"sr" : @[ @"sr_BA", @"sr_ME", @"sr_RS", @"sr_Latn_BA", @"sr_Latn_ME", @"sr_Latn_RS" ],
  892. // European Spanish
  893. @"es_ES" : @[ @"es", @"es_ES", @"es-ES" ],
  894. // Mexican Spanish
  895. @"es_MX" : @[ @"es-MX", @"es_MX", @"es_US", @"es-US" ],
  896. // Latin American Spanish
  897. @"es_419" : @[
  898. @"es_AR", @"es_BO", @"es_CL", @"es_CO", @"es_CR", @"es_DO", @"es_EC",
  899. @"es_SV", @"es_GT", @"es_HN", @"es_NI", @"es_PA", @"es_PY", @"es_PE",
  900. @"es_PR", @"es_UY", @"es_VE", @"es-AR", @"es-CL", @"es-CO"
  901. ],
  902. // Thai
  903. @"th" : @[ @"th", @"th_TH", @"th_TH_TH" ],
  904. };
  905. }
  906. #pragma mark - Utilities used by InstanceID
  907. + (NSString *)FIRMessagingSDKVersion {
  908. return FIRFirebaseVersion();
  909. }
  910. + (NSString *)FIRMessagingSDKCurrentLocale {
  911. return [self currentLocale];
  912. }
  913. #pragma mark - Force Category Linking
  914. #if SWIFT_PACKAGE || COCOAPODS || FIREBASE_BUILD_CARTHAGE || FIREBASE_BUILD_ZIP_FILE
  915. extern void FIRInclude_FIRMessaging_ExtensionHelper_Category(void);
  916. #endif // SWIFT_PACKAGE || COCOAPODS || FIREBASE_BUILD_CARTHAGE || FIREBASE_BUILD_ZIP_FILE
  917. extern void FIRInclude_NSDictionary_FIRMessaging_Category(void);
  918. extern void FIRInclude_NSError_FIRMessaging_Category(void);
  919. /// Does nothing when called, and not meant to be called.
  920. ///
  921. /// This method forces the linker to include categories even if
  922. /// users do not include the '-ObjC' linker flag in their project.
  923. + (void)noop {
  924. #if SWIFT_PACKAGE || COCOAPODS || FIREBASE_BUILD_CARTHAGE || FIREBASE_BUILD_ZIP_FILE
  925. FIRInclude_FIRMessaging_ExtensionHelper_Category();
  926. #endif // SWIFT_PACKAGE || COCOAPODS || FIREBASE_BUILD_CARTHAGE || FIREBASE_BUILD_ZIP_FILE
  927. FIRInclude_NSDictionary_FIRMessaging_Category();
  928. FIRInclude_NSError_FIRMessaging_Category();
  929. }
  930. @end