FIRMessaging.m 44 KB

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