FIRMessaging.m 44 KB

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