FIRMessaging.m 43 KB

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