FIRMessaging.m 44 KB

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