FIRMessaging.m 42 KB

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