FIRMessaging.m 43 KB

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