FIRMessaging.m 43 KB

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