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