FIRMessaging.m 43 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067
  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. const NSNotificationName FIRMessagingRegistrationTokenRefreshedNotification =
  48. @"com.firebase.messaging.notif.fcm-token-refreshed";
  49. NSString *const kFIRMessagingUserDefaultsKeyAutoInitEnabled =
  50. @"com.firebase.messaging.auto-init.enabled"; // Auto Init Enabled key stored in NSUserDefaults
  51. NSString *const kFIRMessagingPlistAutoInitEnabled =
  52. @"FirebaseMessagingAutoInitEnabled"; // Auto Init Enabled key stored in Info.plist
  53. NSString *const FIRMessagingErrorDomain = @"com.google.fcm";
  54. const BOOL FIRMessagingIsAPNSSyncMessage(NSDictionary *message) {
  55. if ([message[kFIRMessagingMessageViaAPNSRootKey] isKindOfClass:[NSDictionary class]]) {
  56. NSDictionary *aps = message[kFIRMessagingMessageViaAPNSRootKey];
  57. if (aps && [aps isKindOfClass:[NSDictionary class]]) {
  58. return [aps[kFIRMessagingMessageAPNSContentAvailableKey] boolValue];
  59. }
  60. }
  61. return NO;
  62. }
  63. BOOL FIRMessagingIsContextManagerMessage(NSDictionary *message) {
  64. return [FIRMessagingContextManagerService isContextManagerMessage:message];
  65. }
  66. @interface FIRMessagingMessageInfo ()
  67. @property(nonatomic, readwrite, assign) FIRMessagingMessageStatus status;
  68. @end
  69. @implementation FIRMessagingMessageInfo
  70. - (instancetype)init {
  71. FIRMessagingInvalidateInitializer();
  72. }
  73. - (instancetype)initWithStatus:(FIRMessagingMessageStatus)status {
  74. self = [super init];
  75. if (self) {
  76. _status = status;
  77. }
  78. return self;
  79. }
  80. @end
  81. @interface FIRMessaging () <GULReachabilityDelegate>
  82. // FIRApp properties
  83. @property(nonatomic, readwrite, strong) NSData *apnsTokenData;
  84. @property(nonatomic, readwrite, strong) FIRMessagingClient *client;
  85. @property(nonatomic, readwrite, strong) GULReachabilityChecker *reachability;
  86. @property(nonatomic, readwrite, strong) FIRMessagingPubSub *pubsub;
  87. @property(nonatomic, readwrite, strong) FIRMessagingRmqManager *rmq2Manager;
  88. @property(nonatomic, readwrite, strong) FIRMessagingSyncMessageManager *syncMessageManager;
  89. @property(nonatomic, readwrite, strong) GULUserDefaults *messagingUserDefaults;
  90. @property(nonatomic, readwrite, strong) FIRInstallations *installations;
  91. @property(nonatomic, readwrite, strong) FIRMessagingTokenManager *tokenManager;
  92. @property(nonatomic, readwrite, strong) FIRHeartbeatLogger *heartbeatLogger;
  93. /// Message ID's logged for analytics. This prevents us from logging the same message twice
  94. /// which can happen if the user inadvertently calls `appDidReceiveMessage` along with us
  95. /// calling it implicitly during swizzling.
  96. @property(nonatomic, readwrite, strong) NSMutableSet *loggedMessageIDs;
  97. @property(nonatomic, readwrite, strong) id<FIRAnalyticsInterop> _Nullable analytics;
  98. @end
  99. @interface FIRMessaging () <FIRMessagingInterop, FIRLibrary>
  100. @end
  101. @implementation FIRMessaging
  102. + (FIRMessaging *)messaging {
  103. FIRApp *defaultApp = [FIRApp defaultApp]; // Missing configure will be logged here.
  104. id<FIRMessagingInterop> instance = FIR_COMPONENT(FIRMessagingInterop, defaultApp.container);
  105. // We know the instance coming from the container is a FIRMessaging instance, cast it and move on.
  106. return (FIRMessaging *)instance;
  107. }
  108. + (FIRMessagingExtensionHelper *)extensionHelper {
  109. static dispatch_once_t once;
  110. static FIRMessagingExtensionHelper *extensionHelper;
  111. dispatch_once(&once, ^{
  112. extensionHelper = [[FIRMessagingExtensionHelper alloc] init];
  113. });
  114. return extensionHelper;
  115. }
  116. #pragma clang diagnostic push
  117. #pragma clang diagnostic ignored "-Wdeprecated-declarations"
  118. - (instancetype)initWithAnalytics:(nullable id<FIRAnalyticsInterop>)analytics
  119. userDefaults:(GULUserDefaults *)defaults
  120. heartbeatLogger:(FIRHeartbeatLogger *)heartbeatLogger {
  121. #pragma clang diagnostic pop
  122. self = [super init];
  123. if (self != nil) {
  124. _loggedMessageIDs = [NSMutableSet set];
  125. _messagingUserDefaults = defaults;
  126. _analytics = analytics;
  127. _heartbeatLogger = heartbeatLogger;
  128. }
  129. return self;
  130. }
  131. - (void)dealloc {
  132. [self.reachability stop];
  133. [[NSNotificationCenter defaultCenter] removeObserver:self];
  134. [self teardown];
  135. }
  136. #pragma mark - Config
  137. + (void)load {
  138. [FIRApp registerInternalLibrary:(Class<FIRLibrary>)self withName:@"fire-fcm"];
  139. }
  140. + (nonnull NSArray<FIRComponent *> *)componentsToRegister {
  141. FIRDependency *analyticsDep = [FIRDependency dependencyWithProtocol:@protocol(FIRAnalyticsInterop)
  142. isRequired:NO];
  143. FIRComponentCreationBlock creationBlock =
  144. ^id _Nullable(FIRComponentContainer *container, BOOL *isCacheable) {
  145. if (!container.app.isDefaultApp) {
  146. // Only start for the default FIRApp.
  147. FIRMessagingLoggerDebug(kFIRMessagingMessageCodeFIRApp001,
  148. @"Firebase Messaging only works with the default app.");
  149. return nil;
  150. }
  151. // Ensure it's cached so it returns the same instance every time messaging is called.
  152. *isCacheable = YES;
  153. id<FIRAnalyticsInterop> analytics = FIR_COMPONENT(FIRAnalyticsInterop, container);
  154. #pragma clang diagnostic push
  155. #pragma clang diagnostic ignored "-Wdeprecated-declarations"
  156. FIRMessaging *messaging =
  157. [[FIRMessaging alloc] initWithAnalytics:analytics
  158. userDefaults:[GULUserDefaults standardUserDefaults]
  159. heartbeatLogger:container.app.heartbeatLogger];
  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:FIRMessagingErrorDomain
  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 // TARGET_OS_WATCH
  189. if (![GULAppEnvironmentUtil isAppExtension]) {
  190. [self didCompleteConfigure];
  191. }
  192. #endif // TARGET_OS_WATCH
  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. // Before fetching FCM token, confirm there is an APNS token to avoid validation error
  201. // This error is innocuous since we refetch after APNS token is set but it can seem alarming
  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] && self.APNSToken) {
  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 && self.APNSToken) {
  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 =
  247. [[FIRMessagingTokenManager alloc] initWithHeartbeatLogger:self.heartbeatLogger];
  248. self.installations = [FIRInstallations installations];
  249. [self setupTopics];
  250. // Print the library version for logging.
  251. NSString *currentLibraryVersion = FIRFirebaseVersion();
  252. FIRMessagingLoggerInfo(kFIRMessagingMessageCodeMessagingPrintLibraryVersion,
  253. @"FIRMessaging library version %@", currentLibraryVersion);
  254. NSString *hostname = kFIRMessagingReachabilityHostname;
  255. self.reachability = [[GULReachabilityChecker alloc] initWithReachabilityDelegate:self
  256. withHost:hostname];
  257. [self.reachability start];
  258. // setup FIRMessaging objects
  259. [self setupRmqManager];
  260. [self setupSyncMessageManager];
  261. }
  262. - (void)setupFileManagerSubDirectory {
  263. if (![[self class] hasSubDirectory:kFIRMessagingSubDirectoryName]) {
  264. [[self class] createSubDirectory:kFIRMessagingSubDirectoryName];
  265. }
  266. if (![[self class] hasSubDirectory:kFIRMessagingInstanceIDSubDirectoryName]) {
  267. [[self class] createSubDirectory:kFIRMessagingInstanceIDSubDirectoryName];
  268. }
  269. }
  270. - (void)setupNotificationListeners {
  271. // To prevent multiple notifications remove self as observer for all events.
  272. NSNotificationCenter *center = [NSNotificationCenter defaultCenter];
  273. [center removeObserver:self];
  274. [center addObserver:self
  275. selector:@selector(defaultFCMTokenWasRefreshed:)
  276. name:kFIRMessagingRegistrationTokenRefreshNotification
  277. object:nil];
  278. }
  279. - (void)setupRmqManager {
  280. self.rmq2Manager = [[FIRMessagingRmqManager alloc] initWithDatabaseName:@"rmq2"];
  281. [self.rmq2Manager loadRmqId];
  282. }
  283. - (void)setupTopics {
  284. self.pubsub = [[FIRMessagingPubSub alloc] initWithTokenManager:self.tokenManager];
  285. }
  286. - (void)setupSyncMessageManager {
  287. self.syncMessageManager =
  288. [[FIRMessagingSyncMessageManager alloc] initWithRmqManager:self.rmq2Manager];
  289. [self.syncMessageManager removeExpiredSyncMessages];
  290. }
  291. - (void)teardown {
  292. self.pubsub = nil;
  293. self.syncMessageManager = nil;
  294. self.rmq2Manager = nil;
  295. FIRMessagingLoggerDebug(kFIRMessagingMessageCodeMessaging001, @"Did successfully teardown");
  296. }
  297. #pragma mark - Messages
  298. - (FIRMessagingMessageInfo *)appDidReceiveMessage:(NSDictionary *)message {
  299. if (!message.count) {
  300. return [[FIRMessagingMessageInfo alloc] initWithStatus:FIRMessagingMessageStatusUnknown];
  301. }
  302. // For downstream messages that go via MCS we should strip out this key before sending
  303. // the message to the device.
  304. BOOL isOldMessage = NO;
  305. NSString *messageID = message[kFIRMessagingMessageIDKey];
  306. if (messageID.length) {
  307. [self.rmq2Manager saveS2dMessageWithRmqId:messageID];
  308. BOOL isSyncMessage = FIRMessagingIsAPNSSyncMessage(message);
  309. if (isSyncMessage) {
  310. isOldMessage = [self.syncMessageManager didReceiveAPNSSyncMessage:message];
  311. }
  312. // Prevent duplicates by keeping a cache of all the logged messages during each session.
  313. // The duplicates only happen when the 3P app calls `appDidReceiveMessage:` along with
  314. // us swizzling their implementation to call the same method implicitly.
  315. // We need to rule out the contextual message because it shares the same message ID
  316. // as the local notification it will schedule. And because it is also a APNSSync message
  317. // its duplication is already checked previously.
  318. if (!isOldMessage && !FIRMessagingIsContextManagerMessage(message)) {
  319. isOldMessage = [self.loggedMessageIDs containsObject:messageID];
  320. if (!isOldMessage) {
  321. [self.loggedMessageIDs addObject:messageID];
  322. }
  323. }
  324. }
  325. if (!isOldMessage) {
  326. [FIRMessagingAnalytics logMessage:message toAnalytics:_analytics];
  327. [self handleContextManagerMessage:message];
  328. [self handleIncomingLinkIfNeededFromMessage:message];
  329. }
  330. return [[FIRMessagingMessageInfo alloc] initWithStatus:FIRMessagingMessageStatusNew];
  331. }
  332. - (BOOL)handleContextManagerMessage:(NSDictionary *)message {
  333. if (FIRMessagingIsContextManagerMessage(message)) {
  334. return [FIRMessagingContextManagerService handleContextManagerMessage:message];
  335. }
  336. return NO;
  337. }
  338. - (void)handleIncomingLinkIfNeededFromMessage:(NSDictionary *)message {
  339. #if TARGET_OS_IOS || TARGET_OS_TV || TARGET_OS_VISION
  340. NSURL *url = [self linkURLFromMessage:message];
  341. if (url == nil) {
  342. return;
  343. }
  344. if (![NSThread isMainThread]) {
  345. dispatch_async(dispatch_get_main_queue(), ^{
  346. [self handleIncomingLinkIfNeededFromMessage:message];
  347. });
  348. return;
  349. }
  350. UIApplication *application = [GULAppDelegateSwizzler sharedApplication];
  351. if (!application) {
  352. return;
  353. }
  354. id<UIApplicationDelegate> appDelegate = application.delegate;
  355. SEL continueUserActivitySelector = @selector(application:
  356. continueUserActivity:restorationHandler:);
  357. SEL openURLWithOptionsSelector = @selector(application:openURL:options:);
  358. SEL openURLWithSourceApplicationSelector = @selector(application:
  359. openURL:sourceApplication:annotation:);
  360. #if TARGET_OS_IOS
  361. SEL handleOpenURLSelector = @selector(application:handleOpenURL:);
  362. #endif // TARGET_OS_IOS
  363. // Due to FIRAAppDelegateProxy swizzling, this selector will most likely get chosen, whether or
  364. // not the actual application has implemented
  365. // |application:continueUserActivity:restorationHandler:|. A warning will be displayed to the user
  366. // if they haven't implemented it.
  367. if ([NSUserActivity class] != nil &&
  368. [appDelegate respondsToSelector:continueUserActivitySelector]) {
  369. NSUserActivity *userActivity =
  370. [[NSUserActivity alloc] initWithActivityType:NSUserActivityTypeBrowsingWeb];
  371. userActivity.webpageURL = url;
  372. [appDelegate application:application
  373. continueUserActivity:userActivity
  374. restorationHandler:^(NSArray *_Nullable restorableObjects){
  375. // Do nothing, as we don't support the app calling this block
  376. }];
  377. } else if ([appDelegate respondsToSelector:openURLWithOptionsSelector]) {
  378. [appDelegate application:application openURL:url options:@{}];
  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 // TARGET_OS_IOS
  396. }
  397. #endif // TARGET_OS_IOS || TARGET_OS_TV || TARGET_OS_VISION
  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. @"'%@'."
  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