FIRMessaging.m 44 KB

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