FIRMessaging.m 44 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144
  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. #if !TARGET_OS_WATCH
  230. // Print the library version for logging.
  231. NSString *currentLibraryVersion = FIRMessagingCurrentLibraryVersion();
  232. FIRMessagingLoggerInfo(kFIRMessagingMessageCodeMessagingPrintLibraryVersion,
  233. @"FIRMessaging library version %@", currentLibraryVersion);
  234. [self setupReceiver];
  235. NSString *hostname = kFIRMessagingReachabilityHostname;
  236. self.reachability = [[GULReachabilityChecker alloc] initWithReachabilityDelegate:self
  237. withHost:hostname];
  238. [self.reachability start];
  239. // setup FIRMessaging objects
  240. [self setupRmqManager];
  241. [self setupClient];
  242. [self setupSyncMessageManager];
  243. [self setupDataMessageManager];
  244. [self setupTopics];
  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. if (!self.client) {
  295. FIRMessagingLoggerWarn(kFIRMessagingMessageCodeInvalidClient,
  296. @"Invalid nil client before init pubsub.");
  297. }
  298. self.pubsub = [[FIRMessagingPubSub alloc] initWithClient:self.client];
  299. }
  300. - (void)setupSyncMessageManager {
  301. self.syncMessageManager =
  302. [[FIRMessagingSyncMessageManager alloc] initWithRmqManager:self.rmq2Manager];
  303. [self.syncMessageManager removeExpiredSyncMessages];
  304. }
  305. - (void)teardown {
  306. [self.client teardown];
  307. self.pubsub = nil;
  308. self.syncMessageManager = nil;
  309. self.rmq2Manager = nil;
  310. self.dataMessageManager = nil;
  311. self.client = nil;
  312. FIRMessagingLoggerDebug(kFIRMessagingMessageCodeMessaging001, @"Did successfully teardown");
  313. }
  314. #pragma mark - Messages
  315. - (FIRMessagingMessageInfo *)appDidReceiveMessage:(NSDictionary *)message {
  316. if (!message.count) {
  317. return [[FIRMessagingMessageInfo alloc] initWithStatus:FIRMessagingMessageStatusUnknown];
  318. }
  319. // For downstream messages that go via MCS we should strip out this key before sending
  320. // the message to the device.
  321. BOOL isOldMessage = NO;
  322. NSString *messageID = message[kFIRMessagingMessageIDKey];
  323. if (messageID.length) {
  324. [self.rmq2Manager saveS2dMessageWithRmqId:messageID];
  325. BOOL isSyncMessage = FIRMessagingIsAPNSSyncMessage(message);
  326. if (isSyncMessage) {
  327. isOldMessage = [self.syncMessageManager didReceiveAPNSSyncMessage:message];
  328. }
  329. // Prevent duplicates by keeping a cache of all the logged messages during each session.
  330. // The duplicates only happen when the 3P app calls `appDidReceiveMessage:` along with
  331. // us swizzling their implementation to call the same method implicitly.
  332. // We need to rule out the contextual message because it shares the same message ID
  333. // as the local notification it will schedule. And because it is also a APNSSync message
  334. // its duplication is already checked previously.
  335. if (!isOldMessage && !FIRMessagingIsContextManagerMessage(message)) {
  336. isOldMessage = [self.loggedMessageIDs containsObject:messageID];
  337. if (!isOldMessage) {
  338. [self.loggedMessageIDs addObject:messageID];
  339. }
  340. }
  341. }
  342. if (!isOldMessage) {
  343. [FIRMessagingAnalytics logMessage:message toAnalytics:_analytics];
  344. [self handleContextManagerMessage:message];
  345. [self handleIncomingLinkIfNeededFromMessage:message];
  346. }
  347. return [[FIRMessagingMessageInfo alloc] initWithStatus:FIRMessagingMessageStatusNew];
  348. }
  349. - (BOOL)handleContextManagerMessage:(NSDictionary *)message {
  350. if (FIRMessagingIsContextManagerMessage(message)) {
  351. return [FIRMessagingContextManagerService handleContextManagerMessage:message];
  352. }
  353. return NO;
  354. }
  355. - (void)handleIncomingLinkIfNeededFromMessage:(NSDictionary *)message {
  356. #if TARGET_OS_IOS || TARGET_OS_TV
  357. NSURL *url = [self linkURLFromMessage:message];
  358. if (url == nil) {
  359. return;
  360. }
  361. if (![NSThread isMainThread]) {
  362. dispatch_async(dispatch_get_main_queue(), ^{
  363. [self handleIncomingLinkIfNeededFromMessage:message];
  364. });
  365. return;
  366. }
  367. UIApplication *application = [GULAppDelegateSwizzler sharedApplication];
  368. if (!application) {
  369. return;
  370. }
  371. id<UIApplicationDelegate> appDelegate = application.delegate;
  372. SEL continueUserActivitySelector = @selector(application:
  373. continueUserActivity:restorationHandler:);
  374. SEL openURLWithOptionsSelector = @selector(application:openURL:options:);
  375. SEL openURLWithSourceApplicationSelector = @selector(application:
  376. openURL:sourceApplication:annotation:);
  377. #if TARGET_OS_IOS
  378. SEL handleOpenURLSelector = @selector(application:handleOpenURL:);
  379. #endif
  380. // Due to FIRAAppDelegateProxy swizzling, this selector will most likely get chosen, whether or
  381. // not the actual application has implemented
  382. // |application:continueUserActivity:restorationHandler:|. A warning will be displayed to the user
  383. // if they haven't implemented it.
  384. if ([NSUserActivity class] != nil &&
  385. [appDelegate respondsToSelector:continueUserActivitySelector]) {
  386. NSUserActivity *userActivity =
  387. [[NSUserActivity alloc] initWithActivityType:NSUserActivityTypeBrowsingWeb];
  388. userActivity.webpageURL = url;
  389. [appDelegate application:application
  390. continueUserActivity:userActivity
  391. restorationHandler:^(NSArray *_Nullable restorableObjects){
  392. // Do nothing, as we don't support the app calling this block
  393. }];
  394. } else if ([appDelegate respondsToSelector:openURLWithOptionsSelector]) {
  395. #pragma clang diagnostic push
  396. #pragma clang diagnostic ignored "-Wunguarded-availability"
  397. [appDelegate application:application openURL:url options:@{}];
  398. #pragma clang diagnostic pop
  399. // Similarly, |application:openURL:sourceApplication:annotation:| will also always be called,
  400. // due to the default swizzling done by FIRAAppDelegateProxy in Firebase Analytics
  401. } else if ([appDelegate respondsToSelector:openURLWithSourceApplicationSelector]) {
  402. #if TARGET_OS_IOS
  403. #pragma clang diagnostic push
  404. #pragma clang diagnostic ignored "-Wdeprecated-declarations"
  405. [appDelegate application:application
  406. openURL:url
  407. sourceApplication:FIRMessagingAppIdentifier()
  408. annotation:@{}];
  409. #pragma clang diagnostic pop
  410. } else if ([appDelegate respondsToSelector:handleOpenURLSelector]) {
  411. #pragma clang diagnostic push
  412. #pragma clang diagnostic ignored "-Wdeprecated-declarations"
  413. [appDelegate application:application handleOpenURL:url];
  414. #pragma clang diagnostic pop
  415. #endif
  416. }
  417. #endif
  418. }
  419. - (NSURL *)linkURLFromMessage:(NSDictionary *)message {
  420. NSString *urlString = message[kFIRMessagingMessageLinkKey];
  421. if (urlString == nil || ![urlString isKindOfClass:[NSString class]] || urlString.length == 0) {
  422. return nil;
  423. }
  424. NSURL *url = [NSURL URLWithString:urlString];
  425. return url;
  426. }
  427. #pragma mark - APNS
  428. - (NSData *)APNSToken {
  429. return self.apnsTokenData;
  430. }
  431. - (void)setAPNSToken:(NSData *)APNSToken {
  432. [self setAPNSToken:APNSToken type:FIRMessagingAPNSTokenTypeUnknown];
  433. }
  434. - (void)setAPNSToken:(NSData *)apnsToken type:(FIRMessagingAPNSTokenType)type {
  435. if ([apnsToken isEqual:self.apnsTokenData]) {
  436. return;
  437. }
  438. self.apnsTokenData = apnsToken;
  439. // Notify InstanceID that APNS Token has been set.
  440. NSDictionary *userInfo = @{kFIRMessagingAPNSTokenType : @(type)};
  441. NSNotification *notification =
  442. [NSNotification notificationWithName:kFIRMessagingAPNSTokenNotification
  443. object:[apnsToken copy]
  444. userInfo:userInfo];
  445. [[NSNotificationQueue defaultQueue] enqueueNotification:notification postingStyle:NSPostASAP];
  446. }
  447. #pragma mark - FCM
  448. - (BOOL)isAutoInitEnabled {
  449. // Defer to the class method since we're just reading from regular userDefaults and we need to
  450. // read this from IID without instantiating the Messaging singleton.
  451. return [[self class] isAutoInitEnabledWithUserDefaults:_messagingUserDefaults];
  452. }
  453. /// Checks if Messaging auto-init is enabled in the user defaults instance passed in. This is
  454. /// exposed as a class property for IID to fetch the property without instantiating an instance of
  455. /// Messaging. Since Messaging can only be used with the default FIRApp, we can have one point of
  456. /// entry without context of which FIRApp instance is being used.
  457. /// ** THIS METHOD IS DEPENDED ON INTERNALLY BY IID USING REFLECTION. PLEASE DO NOT CHANGE THE
  458. /// SIGNATURE, AS IT WOULD BREAK AUTOINIT FUNCTIONALITY WITHIN IID. **
  459. + (BOOL)isAutoInitEnabledWithUserDefaults:(GULUserDefaults *)userDefaults {
  460. // Check storage
  461. id isAutoInitEnabledObject =
  462. [userDefaults objectForKey:kFIRMessagingUserDefaultsKeyAutoInitEnabled];
  463. if (isAutoInitEnabledObject) {
  464. return [isAutoInitEnabledObject boolValue];
  465. }
  466. // Check Info.plist
  467. isAutoInitEnabledObject =
  468. [[NSBundle mainBundle] objectForInfoDictionaryKey:kFIRMessagingPlistAutoInitEnabled];
  469. if (isAutoInitEnabledObject) {
  470. return [isAutoInitEnabledObject boolValue];
  471. }
  472. // If none of above exists, we default to the global switch that comes from FIRApp.
  473. return [[FIRApp defaultApp] isDataCollectionDefaultEnabled];
  474. }
  475. - (void)setAutoInitEnabled:(BOOL)autoInitEnabled {
  476. BOOL isFCMAutoInitEnabled = [self isAutoInitEnabled];
  477. [_messagingUserDefaults setBool:autoInitEnabled
  478. forKey:kFIRMessagingUserDefaultsKeyAutoInitEnabled];
  479. [_messagingUserDefaults synchronize];
  480. if (!isFCMAutoInitEnabled && autoInitEnabled) {
  481. self.defaultFcmToken = self.instanceID.token;
  482. }
  483. }
  484. - (NSString *)FCMToken {
  485. NSString *token = self.defaultFcmToken;
  486. if (!token) {
  487. // We may not have received it from Instance ID yet (via NSNotification), so extract it directly
  488. token = self.instanceID.token;
  489. }
  490. return token;
  491. }
  492. - (void)retrieveFCMTokenForSenderID:(nonnull NSString *)senderID
  493. completion:(nonnull FIRMessagingFCMTokenFetchCompletion)completion {
  494. if (!senderID.length) {
  495. NSString *description = @"Couldn't fetch token because a Sender ID was not supplied. A valid "
  496. @"Sender ID is required to fetch an FCM token";
  497. FIRMessagingLoggerError(kFIRMessagingMessageCodeSenderIDNotSuppliedForTokenFetch, @"%@",
  498. description);
  499. if (completion) {
  500. NSError *error = [NSError messagingErrorWithCode:kFIRMessagingErrorCodeInvalidRequest
  501. failureReason:description];
  502. completion(nil, error);
  503. }
  504. return;
  505. }
  506. NSDictionary *options = nil;
  507. if (self.APNSToken) {
  508. options = @{kFIRMessagingFCMTokenFetchAPNSOption : self.APNSToken};
  509. } else {
  510. FIRMessagingLoggerWarn(kFIRMessagingMessageCodeAPNSTokenNotAvailableDuringTokenFetch,
  511. @"APNS device token not set before retrieving FCM Token for Sender ID "
  512. @"'%@'. Notifications to this FCM Token will not be delivered over APNS."
  513. @"Be sure to re-retrieve the FCM token once the APNS device token is "
  514. @"set.",
  515. senderID);
  516. }
  517. [self.instanceID tokenWithAuthorizedEntity:senderID
  518. scope:kFIRMessagingDefaultTokenScope
  519. options:options
  520. handler:completion];
  521. }
  522. - (void)deleteFCMTokenForSenderID:(nonnull NSString *)senderID
  523. completion:(nonnull FIRMessagingDeleteFCMTokenCompletion)completion {
  524. if (!senderID.length) {
  525. NSString *description = @"Couldn't delete token because a Sender ID was not supplied. A "
  526. @"valid Sender ID is required to delete an FCM token";
  527. FIRMessagingLoggerError(kFIRMessagingMessageCodeSenderIDNotSuppliedForTokenDelete, @"%@",
  528. description);
  529. if (completion) {
  530. NSError *error = [NSError messagingErrorWithCode:kFIRMessagingErrorCodeInvalidRequest
  531. failureReason:description];
  532. completion(error);
  533. }
  534. return;
  535. }
  536. [self.instanceID deleteTokenWithAuthorizedEntity:senderID
  537. scope:kFIRMessagingDefaultTokenScope
  538. handler:completion];
  539. }
  540. #pragma mark - FIRMessagingDelegate helper methods
  541. - (void)setDelegate:(id<FIRMessagingDelegate>)delegate {
  542. _delegate = delegate;
  543. [self validateDelegateConformsToTokenAvailabilityMethods];
  544. }
  545. // Check if the delegate conforms to |didReceiveRegistrationToken:|
  546. // and display a warning to the developer if not.
  547. // NOTE: Once |didReceiveRegistrationToken:| can be made a required method, this
  548. // check can be removed.
  549. - (void)validateDelegateConformsToTokenAvailabilityMethods {
  550. if (self.delegate && ![self.delegate respondsToSelector:@selector(messaging:
  551. didReceiveRegistrationToken:)]) {
  552. FIRMessagingLoggerWarn(kFIRMessagingMessageCodeTokenDelegateMethodsNotImplemented,
  553. @"The object %@ does not respond to "
  554. @"-messaging:didReceiveRegistrationToken:. Please implement "
  555. @"-messaging:didReceiveRegistrationToken: to be provided with an FCM "
  556. @"token.",
  557. self.delegate.description);
  558. }
  559. }
  560. - (void)notifyDelegateOfFCMTokenAvailability {
  561. __weak FIRMessaging *weakSelf = self;
  562. if (![NSThread isMainThread]) {
  563. dispatch_async(dispatch_get_main_queue(), ^{
  564. [weakSelf notifyDelegateOfFCMTokenAvailability];
  565. });
  566. return;
  567. }
  568. if ([self.delegate respondsToSelector:@selector(messaging:didReceiveRegistrationToken:)]) {
  569. [self.delegate messaging:self didReceiveRegistrationToken:self.defaultFcmToken];
  570. }
  571. // Should always trigger the token refresh notification when the delegate method is called
  572. NSNotificationCenter *center = [NSNotificationCenter defaultCenter];
  573. [center postNotificationName:FIRMessagingRegistrationTokenRefreshedNotification
  574. object:self.defaultFcmToken];
  575. }
  576. #pragma mark - Application State Changes
  577. - (void)applicationStateChanged {
  578. #pragma clang diagnostic push
  579. #pragma clang diagnostic ignored "-Wdeprecated-declarations"
  580. if (self.shouldEstablishDirectChannel) {
  581. [self updateAutomaticClientConnection];
  582. }
  583. #pragma clang diagnostic pop
  584. }
  585. #pragma mark - Direct Channel
  586. - (void)setShouldEstablishDirectChannel:(BOOL)shouldEstablishDirectChannel {
  587. if (_shouldEstablishDirectChannel == shouldEstablishDirectChannel) {
  588. return;
  589. }
  590. _shouldEstablishDirectChannel = shouldEstablishDirectChannel;
  591. [self updateAutomaticClientConnection];
  592. }
  593. - (BOOL)isDirectChannelEstablished {
  594. return self.client.isConnectionActive;
  595. }
  596. - (BOOL)shouldBeConnectedAutomatically {
  597. #if TARGET_OS_OSX || TARGET_OS_WATCH
  598. return NO;
  599. #else
  600. // We require a token from Instance ID
  601. NSString *token = self.defaultFcmToken;
  602. // Only on foreground connections
  603. UIApplication *application = [GULAppDelegateSwizzler sharedApplication];
  604. if (!application) {
  605. return NO;
  606. }
  607. UIApplicationState applicationState = application.applicationState;
  608. BOOL shouldBeConnected = _shouldEstablishDirectChannel && (token.length > 0) &&
  609. applicationState == UIApplicationStateActive;
  610. return shouldBeConnected;
  611. #endif
  612. }
  613. - (void)updateAutomaticClientConnection {
  614. if (![NSThread isMainThread]) {
  615. // Call this method from the main thread
  616. dispatch_async(dispatch_get_main_queue(), ^{
  617. [self updateAutomaticClientConnection];
  618. });
  619. return;
  620. }
  621. BOOL shouldBeConnected = [self shouldBeConnectedAutomatically];
  622. if (shouldBeConnected && !self.client.isConnected) {
  623. [self.client connectWithHandler:^(NSError *error) {
  624. if (!error) {
  625. // It means we connected. Fire connection change notification
  626. [self notifyOfDirectChannelConnectionChange];
  627. } else {
  628. FIRMessagingLoggerError(kFIRMessagingMessageCodeDirectChannelConnectionFailed,
  629. @"Failed to connect to direct channel, error: %@\n", error);
  630. }
  631. }];
  632. } else if (!shouldBeConnected && self.client.isConnected) {
  633. [self.client disconnect];
  634. [self notifyOfDirectChannelConnectionChange];
  635. }
  636. }
  637. - (void)notifyOfDirectChannelConnectionChange {
  638. NSNotificationCenter *center = [NSNotificationCenter defaultCenter];
  639. #pragma clang diagnostic push
  640. #pragma clang diagnostic ignored "-Wdeprecated-declarations"
  641. [center postNotificationName:FIRMessagingConnectionStateChangedNotification object:self];
  642. #pragma clang diagnostic pop
  643. }
  644. #pragma mark - Topics
  645. + (NSString *)normalizeTopic:(NSString *)topic {
  646. if (!topic.length) {
  647. return nil;
  648. }
  649. if (![FIRMessagingPubSub hasTopicsPrefix:topic]) {
  650. topic = [FIRMessagingPubSub addPrefixToTopic:topic];
  651. }
  652. if ([FIRMessagingPubSub isValidTopicWithPrefix:topic]) {
  653. return [topic copy];
  654. }
  655. return nil;
  656. }
  657. - (void)subscribeToTopic:(NSString *)topic {
  658. [self subscribeToTopic:topic completion:nil];
  659. }
  660. - (void)subscribeToTopic:(NSString *)topic
  661. completion:(nullable FIRMessagingTopicOperationCompletion)completion {
  662. if ([FIRMessagingPubSub hasTopicsPrefix:topic]) {
  663. FIRMessagingLoggerWarn(kFIRMessagingMessageCodeTopicFormatIsDeprecated,
  664. @"Format '%@' is deprecated. Only '%@' should be used in "
  665. @"subscribeToTopic.",
  666. topic, [FIRMessagingPubSub removePrefixFromTopic:topic]);
  667. }
  668. __weak FIRMessaging *weakSelf = self;
  669. [self.instanceID instanceIDWithHandler:^(FIRInstanceIDResult *_Nullable result,
  670. NSError *_Nullable error) {
  671. if (error) {
  672. FIRMessagingLoggerError(
  673. kFIRMessagingMessageCodeMessaging010,
  674. @"The subscription operation failed due to an error getting the FCM token: %@.", error);
  675. if (completion) {
  676. completion(error);
  677. }
  678. return;
  679. }
  680. FIRMessaging *strongSelf = weakSelf;
  681. NSString *normalizeTopic = [[strongSelf class] normalizeTopic:topic];
  682. if (normalizeTopic.length) {
  683. [strongSelf.pubsub subscribeToTopic:normalizeTopic handler:completion];
  684. return;
  685. }
  686. NSString *failureReason =
  687. [NSString stringWithFormat:@"Cannot parse topic name: '%@'. Will not subscribe.", topic];
  688. FIRMessagingLoggerError(kFIRMessagingMessageCodeMessaging009, @"%@", failureReason);
  689. if (completion) {
  690. completion([NSError messagingErrorWithCode:kFIRMessagingErrorCodeInvalidTopicName
  691. failureReason:failureReason]);
  692. }
  693. }];
  694. }
  695. - (void)unsubscribeFromTopic:(NSString *)topic {
  696. [self unsubscribeFromTopic:topic completion:nil];
  697. }
  698. - (void)unsubscribeFromTopic:(NSString *)topic
  699. completion:(nullable FIRMessagingTopicOperationCompletion)completion {
  700. if ([FIRMessagingPubSub hasTopicsPrefix:topic]) {
  701. FIRMessagingLoggerWarn(kFIRMessagingMessageCodeTopicFormatIsDeprecated,
  702. @"Format '%@' is deprecated. Only '%@' should be used in "
  703. @"unsubscribeFromTopic.",
  704. topic, [FIRMessagingPubSub removePrefixFromTopic:topic]);
  705. }
  706. __weak FIRMessaging *weakSelf = self;
  707. [self.instanceID instanceIDWithHandler:^(FIRInstanceIDResult *_Nullable result,
  708. NSError *_Nullable error) {
  709. if (error) {
  710. FIRMessagingLoggerError(
  711. kFIRMessagingMessageCodeMessaging012,
  712. @"The unsubscription operation failed due to an error getting the FCM token: %@.", error);
  713. if (completion) {
  714. completion(error);
  715. }
  716. return;
  717. }
  718. FIRMessaging *strongSelf = weakSelf;
  719. NSString *normalizeTopic = [[strongSelf class] normalizeTopic:topic];
  720. if (normalizeTopic.length) {
  721. [strongSelf.pubsub unsubscribeFromTopic:normalizeTopic handler:completion];
  722. return;
  723. }
  724. NSString *failureReason =
  725. [NSString stringWithFormat:@"Cannot parse topic name: '%@'. Will not unsubscribe.", topic];
  726. FIRMessagingLoggerError(kFIRMessagingMessageCodeMessaging011, @"%@", failureReason);
  727. if (completion) {
  728. completion([NSError messagingErrorWithCode:kFIRMessagingErrorCodeInvalidTopicName
  729. failureReason:failureReason]);
  730. }
  731. }];
  732. }
  733. #pragma mark - Send
  734. - (void)sendMessage:(NSDictionary *)message
  735. to:(NSString *)to
  736. withMessageID:(NSString *)messageID
  737. timeToLive:(int64_t)ttl {
  738. NSMutableDictionary *fcmMessage = [[self class] createFIRMessagingMessageWithMessage:message
  739. to:to
  740. withID:messageID
  741. timeToLive:ttl
  742. delay:0];
  743. FIRMessagingLoggerInfo(kFIRMessagingMessageCodeMessaging013,
  744. @"Sending message: %@ with id: %@ to %@.", message, messageID, to);
  745. [self.dataMessageManager sendDataMessageStanza:fcmMessage];
  746. }
  747. + (NSMutableDictionary *)createFIRMessagingMessageWithMessage:(NSDictionary *)message
  748. to:(NSString *)to
  749. withID:(NSString *)msgID
  750. timeToLive:(int64_t)ttl
  751. delay:(int)delay {
  752. NSMutableDictionary *fcmMessage = [NSMutableDictionary dictionary];
  753. fcmMessage[kFIRMessagingSendTo] = [to copy];
  754. fcmMessage[kFIRMessagingSendMessageID] = msgID ? [msgID copy] : @"";
  755. fcmMessage[kFIRMessagingSendTTL] = @(ttl);
  756. fcmMessage[kFIRMessagingSendDelay] = @(delay);
  757. fcmMessage[KFIRMessagingSendMessageAppData] =
  758. [NSMutableDictionary dictionaryWithDictionary:message];
  759. return fcmMessage;
  760. }
  761. #pragma mark - IID dependencies
  762. + (NSString *)FIRMessagingSDKVersion {
  763. return FIRMessagingCurrentLibraryVersion();
  764. }
  765. + (NSString *)FIRMessagingSDKCurrentLocale {
  766. return [self currentLocale];
  767. }
  768. #pragma mark - FIRMessagingReceiverDelegate
  769. #pragma clang diagnostic push
  770. #pragma clang diagnostic ignored "-Wdeprecated-declarations"
  771. - (void)receiver:(FIRMessagingReceiver *)receiver
  772. receivedRemoteMessage:(FIRMessagingRemoteMessage *)remoteMessage {
  773. if ([self.delegate respondsToSelector:@selector(messaging:didReceiveMessage:)]) {
  774. [self appDidReceiveMessage:remoteMessage.appData];
  775. #pragma clang diagnostic ignored "-Wunguarded-availability"
  776. [self.delegate messaging:self didReceiveMessage:remoteMessage];
  777. #pragma clang diagnostic pop
  778. } else {
  779. // Delegate methods weren't implemented, so messages are being dropped, log a warning
  780. FIRMessagingLoggerWarn(kFIRMessagingMessageCodeRemoteMessageDelegateMethodNotImplemented,
  781. @"FIRMessaging received data-message, but FIRMessagingDelegate's"
  782. @"-messaging:didReceiveMessage: not implemented");
  783. }
  784. }
  785. #pragma mark - GULReachabilityDelegate
  786. - (void)reachability:(GULReachabilityChecker *)reachability
  787. statusChanged:(GULReachabilityStatus)status {
  788. [self onNetworkStatusChanged];
  789. }
  790. #pragma mark - Network
  791. - (void)onNetworkStatusChanged {
  792. if (![self.client isConnected] && [self isNetworkAvailable]) {
  793. if (self.client.shouldStayConnected) {
  794. FIRMessagingLoggerDebug(kFIRMessagingMessageCodeMessaging014,
  795. @"Attempting to establish direct channel.");
  796. [self.client retryConnectionImmediately:YES];
  797. }
  798. [self.pubsub scheduleSync:YES];
  799. }
  800. }
  801. - (BOOL)isNetworkAvailable {
  802. GULReachabilityStatus status = self.reachability.reachabilityStatus;
  803. return (status == kGULReachabilityViaCellular || status == kGULReachabilityViaWifi);
  804. }
  805. - (FIRMessagingNetworkStatus)networkType {
  806. GULReachabilityStatus status = self.reachability.reachabilityStatus;
  807. if (![self isNetworkAvailable]) {
  808. return kFIRMessagingReachabilityNotReachable;
  809. } else if (status == kGULReachabilityViaCellular) {
  810. return kFIRMessagingReachabilityReachableViaWWAN;
  811. } else {
  812. return kFIRMessagingReachabilityReachableViaWiFi;
  813. }
  814. }
  815. #pragma mark - Notifications
  816. - (void)defaultInstanceIDTokenWasRefreshed:(NSNotification *)notification {
  817. if (notification.object && ![notification.object isKindOfClass:[NSString class]]) {
  818. FIRMessagingLoggerDebug(kFIRMessagingMessageCodeMessaging015,
  819. @"Invalid default FCM token type %@",
  820. NSStringFromClass([notification.object class]));
  821. return;
  822. }
  823. // Retrieve the Instance ID default token, and should notify delegate and
  824. // trigger notification as long as the token is different from previous state.
  825. NSString *oldToken = self.defaultFcmToken;
  826. self.defaultFcmToken = [(NSString *)notification.object copy];
  827. if ((self.defaultFcmToken.length && oldToken.length &&
  828. ![self.defaultFcmToken isEqualToString:oldToken]) ||
  829. self.defaultFcmToken.length != oldToken.length) {
  830. [self notifyDelegateOfFCMTokenAvailability];
  831. [self.pubsub scheduleSync:YES];
  832. #pragma clang diagnostic push
  833. #pragma clang diagnostic ignored "-Wdeprecated-declarations"
  834. if (self.shouldEstablishDirectChannel) {
  835. [self updateAutomaticClientConnection];
  836. }
  837. #pragma clang diagnostic pop
  838. }
  839. }
  840. #pragma mark - Application Support Directory
  841. + (BOOL)hasSubDirectory:(NSString *)subDirectoryName {
  842. NSString *subDirectoryPath = [self pathForSubDirectory:subDirectoryName];
  843. BOOL isDirectory;
  844. if (![[NSFileManager defaultManager] fileExistsAtPath:subDirectoryPath
  845. isDirectory:&isDirectory]) {
  846. return NO;
  847. } else if (!isDirectory) {
  848. return NO;
  849. }
  850. return YES;
  851. }
  852. + (NSString *)pathForSubDirectory:(NSString *)subDirectoryName {
  853. NSArray *directoryPaths =
  854. NSSearchPathForDirectoriesInDomains(FIRMessagingSupportedDirectory(), NSUserDomainMask, YES);
  855. NSString *dirPath = directoryPaths.lastObject;
  856. NSArray *components = @[ dirPath, subDirectoryName ];
  857. return [NSString pathWithComponents:components];
  858. }
  859. + (BOOL)createSubDirectory:(NSString *)subDirectoryName {
  860. NSString *subDirectoryPath = [self pathForSubDirectory:subDirectoryName];
  861. BOOL hasSubDirectory;
  862. if (![[NSFileManager defaultManager] fileExistsAtPath:subDirectoryPath
  863. isDirectory:&hasSubDirectory]) {
  864. NSError *error;
  865. [[NSFileManager defaultManager] createDirectoryAtPath:subDirectoryPath
  866. withIntermediateDirectories:YES
  867. attributes:nil
  868. error:&error];
  869. if (error) {
  870. FIRMessagingLoggerError(kFIRMessagingMessageCodeMessaging017,
  871. @"Cannot create directory %@, error: %@", subDirectoryPath, error);
  872. return NO;
  873. }
  874. } else {
  875. if (!hasSubDirectory) {
  876. FIRMessagingLoggerError(kFIRMessagingMessageCodeMessaging018,
  877. @"Found file instead of directory at %@", subDirectoryPath);
  878. return NO;
  879. }
  880. }
  881. return YES;
  882. }
  883. #pragma mark - Locales
  884. + (NSString *)currentLocale {
  885. NSArray *locales = [self firebaseLocales];
  886. NSArray *preferredLocalizations =
  887. [NSBundle preferredLocalizationsFromArray:locales
  888. forPreferences:[NSLocale preferredLanguages]];
  889. NSString *legalDocsLanguage = [preferredLocalizations firstObject];
  890. // Use en as the default language
  891. return legalDocsLanguage ? legalDocsLanguage : @"en";
  892. }
  893. + (NSArray *)firebaseLocales {
  894. NSMutableArray *locales = [NSMutableArray array];
  895. NSDictionary *localesMap = [self firebaselocalesMap];
  896. for (NSString *key in localesMap) {
  897. [locales addObjectsFromArray:localesMap[key]];
  898. }
  899. return locales;
  900. }
  901. + (NSDictionary *)firebaselocalesMap {
  902. return @{
  903. // Albanian
  904. @"sq" : @[ @"sq_AL" ],
  905. // Belarusian
  906. @"be" : @[ @"be_BY" ],
  907. // Bulgarian
  908. @"bg" : @[ @"bg_BG" ],
  909. // Catalan
  910. @"ca" : @[ @"ca", @"ca_ES" ],
  911. // Croatian
  912. @"hr" : @[ @"hr", @"hr_HR" ],
  913. // Czech
  914. @"cs" : @[ @"cs", @"cs_CZ" ],
  915. // Danish
  916. @"da" : @[ @"da", @"da_DK" ],
  917. // Estonian
  918. @"et" : @[ @"et_EE" ],
  919. // Finnish
  920. @"fi" : @[ @"fi", @"fi_FI" ],
  921. // Hebrew
  922. @"he" : @[ @"he", @"iw_IL" ],
  923. // Hindi
  924. @"hi" : @[ @"hi_IN" ],
  925. // Hungarian
  926. @"hu" : @[ @"hu", @"hu_HU" ],
  927. // Icelandic
  928. @"is" : @[ @"is_IS" ],
  929. // Indonesian
  930. @"id" : @[ @"id", @"in_ID", @"id_ID" ],
  931. // Irish
  932. @"ga" : @[ @"ga_IE" ],
  933. // Korean
  934. @"ko" : @[ @"ko", @"ko_KR", @"ko-KR" ],
  935. // Latvian
  936. @"lv" : @[ @"lv_LV" ],
  937. // Lithuanian
  938. @"lt" : @[ @"lt_LT" ],
  939. // Macedonian
  940. @"mk" : @[ @"mk_MK" ],
  941. // Malay
  942. @"ms" : @[ @"ms_MY" ],
  943. // Maltese
  944. @"mt" : @[ @"mt_MT" ],
  945. // Polish
  946. @"pl" : @[ @"pl", @"pl_PL", @"pl-PL" ],
  947. // Romanian
  948. @"ro" : @[ @"ro", @"ro_RO" ],
  949. // Russian
  950. @"ru" : @[ @"ru_RU", @"ru", @"ru_BY", @"ru_KZ", @"ru-RU" ],
  951. // Slovak
  952. @"sk" : @[ @"sk", @"sk_SK" ],
  953. // Slovenian
  954. @"sl" : @[ @"sl_SI" ],
  955. // Swedish
  956. @"sv" : @[ @"sv", @"sv_SE", @"sv-SE" ],
  957. // Turkish
  958. @"tr" : @[ @"tr", @"tr-TR", @"tr_TR" ],
  959. // Ukrainian
  960. @"uk" : @[ @"uk", @"uk_UA" ],
  961. // Vietnamese
  962. @"vi" : @[ @"vi", @"vi_VN" ],
  963. // The following are groups of locales or locales that sub-divide a
  964. // language).
  965. // Arabic
  966. @"ar" : @[
  967. @"ar", @"ar_DZ", @"ar_BH", @"ar_EG", @"ar_IQ", @"ar_JO", @"ar_KW",
  968. @"ar_LB", @"ar_LY", @"ar_MA", @"ar_OM", @"ar_QA", @"ar_SA", @"ar_SD",
  969. @"ar_SY", @"ar_TN", @"ar_AE", @"ar_YE", @"ar_GB", @"ar-IQ", @"ar_US"
  970. ],
  971. // Simplified Chinese
  972. @"zh_Hans" : @[ @"zh_CN", @"zh_SG", @"zh-Hans" ],
  973. // Traditional Chinese
  974. @"zh_Hant" : @[ @"zh_HK", @"zh_TW", @"zh-Hant", @"zh-HK", @"zh-TW" ],
  975. // Dutch
  976. @"nl" : @[ @"nl", @"nl_BE", @"nl_NL", @"nl-NL" ],
  977. // English
  978. @"en" : @[
  979. @"en", @"en_AU", @"en_CA", @"en_IN", @"en_IE", @"en_MT", @"en_NZ", @"en_PH",
  980. @"en_SG", @"en_ZA", @"en_GB", @"en_US", @"en_AE", @"en-AE", @"en_AS", @"en-AU",
  981. @"en_BD", @"en-CA", @"en_EG", @"en_ES", @"en_GB", @"en-GB", @"en_HK", @"en_ID",
  982. @"en-IN", @"en_NG", @"en-PH", @"en_PK", @"en-SG", @"en-US"
  983. ],
  984. // French
  985. @"fr" :
  986. @[ @"fr", @"fr_BE", @"fr_CA", @"fr_FR", @"fr_LU", @"fr_CH", @"fr-CA", @"fr-FR", @"fr_MA" ],
  987. // German
  988. @"de" : @[ @"de", @"de_AT", @"de_DE", @"de_LU", @"de_CH", @"de-DE" ],
  989. // Greek
  990. @"el" : @[ @"el", @"el_CY", @"el_GR" ],
  991. // Italian
  992. @"it" : @[ @"it", @"it_IT", @"it_CH", @"it-IT" ],
  993. // Japanese
  994. @"ja" : @[ @"ja", @"ja_JP", @"ja_JP_JP", @"ja-JP" ],
  995. // Norwegian
  996. @"no" : @[ @"nb", @"no_NO", @"no_NO_NY", @"nb_NO" ],
  997. // Brazilian Portuguese
  998. @"pt_BR" : @[ @"pt_BR", @"pt-BR" ],
  999. // European Portuguese
  1000. @"pt_PT" : @[ @"pt", @"pt_PT", @"pt-PT" ],
  1001. // Serbian
  1002. @"sr" : @[ @"sr_BA", @"sr_ME", @"sr_RS", @"sr_Latn_BA", @"sr_Latn_ME", @"sr_Latn_RS" ],
  1003. // European Spanish
  1004. @"es_ES" : @[ @"es", @"es_ES", @"es-ES" ],
  1005. // Mexican Spanish
  1006. @"es_MX" : @[ @"es-MX", @"es_MX", @"es_US", @"es-US" ],
  1007. // Latin American Spanish
  1008. @"es_419" : @[
  1009. @"es_AR", @"es_BO", @"es_CL", @"es_CO", @"es_CR", @"es_DO", @"es_EC",
  1010. @"es_SV", @"es_GT", @"es_HN", @"es_NI", @"es_PA", @"es_PY", @"es_PE",
  1011. @"es_PR", @"es_UY", @"es_VE", @"es-AR", @"es-CL", @"es-CO"
  1012. ],
  1013. // Thai
  1014. @"th" : @[ @"th", @"th_TH", @"th_TH_TH" ],
  1015. };
  1016. }
  1017. @end