FIRMessaging.m 44 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159
  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 "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 = @"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(didReceiveDefaultInstanceIDToken:)
  262. name:kFIRMessagingFCMTokenNotification
  263. object:nil];
  264. [center addObserver:self
  265. selector:@selector(defaultInstanceIDTokenWasRefreshed:)
  266. name:kFIRMessagingRegistrationTokenRefreshNotification
  267. object:nil];
  268. #if TARGET_OS_IOS || TARGET_OS_TV
  269. [center addObserver:self
  270. selector:@selector(applicationStateChanged)
  271. name:UIApplicationDidBecomeActiveNotification
  272. object:nil];
  273. [center addObserver:self
  274. selector:@selector(applicationStateChanged)
  275. name:UIApplicationDidEnterBackgroundNotification
  276. object:nil];
  277. #endif
  278. }
  279. - (void)setupReceiver {
  280. self.receiver = [[FIRMessagingReceiver alloc] init];
  281. self.receiver.delegate = self;
  282. }
  283. - (void)setupClient {
  284. self.client = [[FIRMessagingClient alloc] initWithDelegate:self
  285. reachability:self.reachability
  286. rmq2Manager:self.rmq2Manager];
  287. }
  288. - (void)setupDataMessageManager {
  289. self.dataMessageManager =
  290. [[FIRMessagingDataMessageManager alloc] initWithDelegate:self.receiver
  291. client:self.client
  292. rmq2Manager:self.rmq2Manager
  293. syncMessageManager:self.syncMessageManager];
  294. [self.dataMessageManager refreshDelayedMessages];
  295. [self.client setDataMessageManager:self.dataMessageManager];
  296. }
  297. - (void)setupRmqManager {
  298. self.rmq2Manager = [[FIRMessagingRmqManager alloc] initWithDatabaseName:@"rmq2"];
  299. [self.rmq2Manager loadRmqId];
  300. }
  301. - (void)setupTopics {
  302. if (!self.client) {
  303. FIRMessagingLoggerWarn(kFIRMessagingMessageCodeInvalidClient,
  304. @"Invalid nil client before init pubsub.");
  305. }
  306. self.pubsub = [[FIRMessagingPubSub alloc] initWithClient:self.client];
  307. }
  308. - (void)setupSyncMessageManager {
  309. self.syncMessageManager =
  310. [[FIRMessagingSyncMessageManager alloc] initWithRmqManager:self.rmq2Manager];
  311. [self.syncMessageManager removeExpiredSyncMessages];
  312. }
  313. - (void)teardown {
  314. [self.client teardown];
  315. self.pubsub = nil;
  316. self.syncMessageManager = nil;
  317. self.rmq2Manager = nil;
  318. self.dataMessageManager = nil;
  319. self.client = nil;
  320. FIRMessagingLoggerDebug(kFIRMessagingMessageCodeMessaging001, @"Did successfully teardown");
  321. }
  322. #pragma mark - Messages
  323. - (FIRMessagingMessageInfo *)appDidReceiveMessage:(NSDictionary *)message {
  324. if (!message.count) {
  325. return [[FIRMessagingMessageInfo alloc] initWithStatus:FIRMessagingMessageStatusUnknown];
  326. }
  327. // For downstream messages that go via MCS we should strip out this key before sending
  328. // the message to the device.
  329. BOOL isOldMessage = NO;
  330. NSString *messageID = message[kFIRMessagingMessageIDKey];
  331. if (messageID.length) {
  332. [self.rmq2Manager saveS2dMessageWithRmqId:messageID];
  333. BOOL isSyncMessage = FIRMessagingIsAPNSSyncMessage(message);
  334. if (isSyncMessage) {
  335. isOldMessage = [self.syncMessageManager didReceiveAPNSSyncMessage:message];
  336. }
  337. // Prevent duplicates by keeping a cache of all the logged messages during each session.
  338. // The duplicates only happen when the 3P app calls `appDidReceiveMessage:` along with
  339. // us swizzling their implementation to call the same method implicitly.
  340. // We need to rule out the contextual message because it shares the same message ID
  341. // as the local notification it will schedule. And because it is also a APNSSync message
  342. // its duplication is already checked previously.
  343. if (!isOldMessage && !FIRMessagingIsContextManagerMessage(message)) {
  344. isOldMessage = [self.loggedMessageIDs containsObject:messageID];
  345. if (!isOldMessage) {
  346. [self.loggedMessageIDs addObject:messageID];
  347. }
  348. }
  349. }
  350. if (!isOldMessage) {
  351. [FIRMessagingAnalytics logMessage:message toAnalytics:_analytics];
  352. [self handleContextManagerMessage:message];
  353. [self handleIncomingLinkIfNeededFromMessage:message];
  354. }
  355. return [[FIRMessagingMessageInfo alloc] initWithStatus:FIRMessagingMessageStatusNew];
  356. }
  357. - (BOOL)handleContextManagerMessage:(NSDictionary *)message {
  358. if (FIRMessagingIsContextManagerMessage(message)) {
  359. return [FIRMessagingContextManagerService handleContextManagerMessage:message];
  360. }
  361. return NO;
  362. }
  363. - (void)handleIncomingLinkIfNeededFromMessage:(NSDictionary *)message {
  364. #if TARGET_OS_IOS || TARGET_OS_TV
  365. NSURL *url = [self linkURLFromMessage:message];
  366. if (url == nil) {
  367. return;
  368. }
  369. if (![NSThread isMainThread]) {
  370. dispatch_async(dispatch_get_main_queue(), ^{
  371. [self handleIncomingLinkIfNeededFromMessage:message];
  372. });
  373. return;
  374. }
  375. UIApplication *application = [GULAppDelegateSwizzler sharedApplication];
  376. if (!application) {
  377. return;
  378. }
  379. id<UIApplicationDelegate> appDelegate = application.delegate;
  380. SEL continueUserActivitySelector = @selector(application:
  381. continueUserActivity:restorationHandler:);
  382. SEL openURLWithOptionsSelector = @selector(application:openURL:options:);
  383. SEL openURLWithSourceApplicationSelector = @selector(application:
  384. openURL:sourceApplication:annotation:);
  385. #if TARGET_OS_IOS
  386. SEL handleOpenURLSelector = @selector(application:handleOpenURL:);
  387. #endif
  388. // Due to FIRAAppDelegateProxy swizzling, this selector will most likely get chosen, whether or
  389. // not the actual application has implemented
  390. // |application:continueUserActivity:restorationHandler:|. A warning will be displayed to the user
  391. // if they haven't implemented it.
  392. if ([NSUserActivity class] != nil &&
  393. [appDelegate respondsToSelector:continueUserActivitySelector]) {
  394. NSUserActivity *userActivity =
  395. [[NSUserActivity alloc] initWithActivityType:NSUserActivityTypeBrowsingWeb];
  396. userActivity.webpageURL = url;
  397. [appDelegate application:application
  398. continueUserActivity:userActivity
  399. restorationHandler:^(NSArray *_Nullable restorableObjects){
  400. // Do nothing, as we don't support the app calling this block
  401. }];
  402. } else if ([appDelegate respondsToSelector:openURLWithOptionsSelector]) {
  403. #pragma clang diagnostic push
  404. #pragma clang diagnostic ignored "-Wunguarded-availability"
  405. [appDelegate application:application openURL:url options:@{}];
  406. #pragma clang diagnostic pop
  407. // Similarly, |application:openURL:sourceApplication:annotation:| will also always be called,
  408. // due to the default swizzling done by FIRAAppDelegateProxy in Firebase Analytics
  409. } else if ([appDelegate respondsToSelector:openURLWithSourceApplicationSelector]) {
  410. #if TARGET_OS_IOS
  411. #pragma clang diagnostic push
  412. #pragma clang diagnostic ignored "-Wdeprecated-declarations"
  413. [appDelegate application:application
  414. openURL:url
  415. sourceApplication:FIRMessagingAppIdentifier()
  416. annotation:@{}];
  417. #pragma clang diagnostic pop
  418. } else if ([appDelegate respondsToSelector:handleOpenURLSelector]) {
  419. #pragma clang diagnostic push
  420. #pragma clang diagnostic ignored "-Wdeprecated-declarations"
  421. [appDelegate application:application handleOpenURL:url];
  422. #pragma clang diagnostic pop
  423. #endif
  424. }
  425. #endif
  426. }
  427. - (NSURL *)linkURLFromMessage:(NSDictionary *)message {
  428. NSString *urlString = message[kFIRMessagingMessageLinkKey];
  429. if (urlString == nil || ![urlString isKindOfClass:[NSString class]] || urlString.length == 0) {
  430. return nil;
  431. }
  432. NSURL *url = [NSURL URLWithString:urlString];
  433. return url;
  434. }
  435. #pragma mark - APNS
  436. - (NSData *)APNSToken {
  437. return self.apnsTokenData;
  438. }
  439. - (void)setAPNSToken:(NSData *)APNSToken {
  440. [self setAPNSToken:APNSToken type:FIRMessagingAPNSTokenTypeUnknown];
  441. }
  442. - (void)setAPNSToken:(NSData *)apnsToken type:(FIRMessagingAPNSTokenType)type {
  443. if ([apnsToken isEqual:self.apnsTokenData]) {
  444. return;
  445. }
  446. self.apnsTokenData = apnsToken;
  447. // Notify InstanceID that APNS Token has been set.
  448. NSDictionary *userInfo = @{kFIRMessagingAPNSTokenType : @(type)};
  449. NSNotification *notification =
  450. [NSNotification notificationWithName:kFIRMessagingAPNSTokenNotification
  451. object:[apnsToken copy]
  452. userInfo:userInfo];
  453. [[NSNotificationQueue defaultQueue] enqueueNotification:notification postingStyle:NSPostASAP];
  454. }
  455. #pragma mark - FCM
  456. - (BOOL)isAutoInitEnabled {
  457. // Defer to the class method since we're just reading from regular userDefaults and we need to
  458. // read this from IID without instantiating the Messaging singleton.
  459. return [[self class] isAutoInitEnabledWithUserDefaults:_messagingUserDefaults];
  460. }
  461. /// Checks if Messaging auto-init is enabled in the user defaults instance passed in. This is
  462. /// exposed as a class property for IID to fetch the property without instantiating an instance of
  463. /// Messaging. Since Messaging can only be used with the default FIRApp, we can have one point of
  464. /// entry without context of which FIRApp instance is being used.
  465. /// ** THIS METHOD IS DEPENDED ON INTERNALLY BY IID USING REFLECTION. PLEASE DO NOT CHANGE THE
  466. /// SIGNATURE, AS IT WOULD BREAK AUTOINIT FUNCTIONALITY WITHIN IID. **
  467. + (BOOL)isAutoInitEnabledWithUserDefaults:(GULUserDefaults *)userDefaults {
  468. // Check storage
  469. id isAutoInitEnabledObject =
  470. [userDefaults objectForKey:kFIRMessagingUserDefaultsKeyAutoInitEnabled];
  471. if (isAutoInitEnabledObject) {
  472. return [isAutoInitEnabledObject boolValue];
  473. }
  474. // Check Info.plist
  475. isAutoInitEnabledObject =
  476. [[NSBundle mainBundle] objectForInfoDictionaryKey:kFIRMessagingPlistAutoInitEnabled];
  477. if (isAutoInitEnabledObject) {
  478. return [isAutoInitEnabledObject boolValue];
  479. }
  480. // If none of above exists, we default to the global switch that comes from FIRApp.
  481. return [[FIRApp defaultApp] isDataCollectionDefaultEnabled];
  482. }
  483. - (void)setAutoInitEnabled:(BOOL)autoInitEnabled {
  484. BOOL isFCMAutoInitEnabled = [self isAutoInitEnabled];
  485. [_messagingUserDefaults setBool:autoInitEnabled
  486. forKey:kFIRMessagingUserDefaultsKeyAutoInitEnabled];
  487. [_messagingUserDefaults synchronize];
  488. if (!isFCMAutoInitEnabled && autoInitEnabled) {
  489. self.defaultFcmToken = self.instanceID.token;
  490. }
  491. }
  492. - (NSString *)FCMToken {
  493. NSString *token = self.defaultFcmToken;
  494. if (!token) {
  495. // We may not have received it from Instance ID yet (via NSNotification), so extract it directly
  496. token = self.instanceID.token;
  497. }
  498. return token;
  499. }
  500. - (void)retrieveFCMTokenForSenderID:(nonnull NSString *)senderID
  501. completion:(nonnull FIRMessagingFCMTokenFetchCompletion)completion {
  502. if (!senderID.length) {
  503. FIRMessagingLoggerError(kFIRMessagingMessageCodeSenderIDNotSuppliedForTokenFetch,
  504. @"Sender ID not supplied. It is required for a token fetch, "
  505. @"to identify the sender.");
  506. if (completion) {
  507. NSString *description = @"Couldn't fetch token because a Sender ID was not supplied. A valid "
  508. @"Sender ID is required to fetch an FCM token";
  509. NSError *error = [NSError fcm_errorWithCode:FIRMessagingErrorInvalidRequest
  510. userInfo:@{NSLocalizedDescriptionKey : description}];
  511. completion(nil, error);
  512. }
  513. return;
  514. }
  515. NSDictionary *options = nil;
  516. if (self.APNSToken) {
  517. options = @{kFIRMessagingFCMTokenFetchAPNSOption : self.APNSToken};
  518. } else {
  519. FIRMessagingLoggerWarn(kFIRMessagingMessageCodeAPNSTokenNotAvailableDuringTokenFetch,
  520. @"APNS device token not set before retrieving FCM Token for Sender ID "
  521. @"'%@'. Notifications to this FCM Token will not be delivered over APNS."
  522. @"Be sure to re-retrieve the FCM token once the APNS device token is "
  523. @"set.",
  524. senderID);
  525. }
  526. [self.instanceID tokenWithAuthorizedEntity:senderID
  527. scope:kFIRMessagingDefaultTokenScope
  528. options:options
  529. handler:completion];
  530. }
  531. - (void)deleteFCMTokenForSenderID:(nonnull NSString *)senderID
  532. completion:(nonnull FIRMessagingDeleteFCMTokenCompletion)completion {
  533. if (!senderID.length) {
  534. FIRMessagingLoggerError(kFIRMessagingMessageCodeSenderIDNotSuppliedForTokenDelete,
  535. @"Sender ID not supplied. It is required to delete an FCM token.");
  536. if (completion) {
  537. NSString *description = @"Couldn't delete token because a Sender ID was not supplied. A "
  538. @"valid Sender ID is required to delete an FCM token";
  539. NSError *error = [NSError fcm_errorWithCode:FIRMessagingErrorInvalidRequest
  540. userInfo:@{NSLocalizedDescriptionKey : description}];
  541. completion(error);
  542. }
  543. return;
  544. }
  545. [self.instanceID deleteTokenWithAuthorizedEntity:senderID
  546. scope:kFIRMessagingDefaultTokenScope
  547. handler:completion];
  548. }
  549. #pragma mark - FIRMessagingDelegate helper methods
  550. - (void)setDelegate:(id<FIRMessagingDelegate>)delegate {
  551. _delegate = delegate;
  552. [self validateDelegateConformsToTokenAvailabilityMethods];
  553. }
  554. // Check if the delegate conforms to |didReceiveRegistrationToken:|
  555. // and display a warning to the developer if not.
  556. // NOTE: Once |didReceiveRegistrationToken:| can be made a required method, this
  557. // check can be removed.
  558. - (void)validateDelegateConformsToTokenAvailabilityMethods {
  559. if (self.delegate && ![self.delegate respondsToSelector:@selector(messaging:
  560. didReceiveRegistrationToken:)]) {
  561. FIRMessagingLoggerWarn(kFIRMessagingMessageCodeTokenDelegateMethodsNotImplemented,
  562. @"The object %@ does not respond to "
  563. @"-messaging:didReceiveRegistrationToken:. Please implement "
  564. @"-messaging:didReceiveRegistrationToken: to be provided with an FCM "
  565. @"token.",
  566. self.delegate.description);
  567. }
  568. }
  569. - (void)notifyDelegateOfFCMTokenAvailability {
  570. __weak FIRMessaging *weakSelf = self;
  571. if (![NSThread isMainThread]) {
  572. dispatch_async(dispatch_get_main_queue(), ^{
  573. [weakSelf notifyDelegateOfFCMTokenAvailability];
  574. });
  575. return;
  576. }
  577. if ([self.delegate respondsToSelector:@selector(messaging:didReceiveRegistrationToken:)]) {
  578. [self.delegate messaging:self didReceiveRegistrationToken:self.defaultFcmToken];
  579. }
  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)didReceiveDefaultInstanceIDToken:(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. NSString *oldToken = self.defaultFcmToken;
  825. self.defaultFcmToken = [(NSString *)notification.object copy];
  826. if (self.defaultFcmToken && ![self.defaultFcmToken isEqualToString:oldToken]) {
  827. [self notifyDelegateOfFCMTokenAvailability];
  828. }
  829. [self.pubsub scheduleSync:YES];
  830. #pragma clang diagnostic push
  831. #pragma clang diagnostic ignored "-Wdeprecated-declarations"
  832. if (self.shouldEstablishDirectChannel) {
  833. [self updateAutomaticClientConnection];
  834. }
  835. #pragma clang diagnostic pop
  836. }
  837. - (void)defaultInstanceIDTokenWasRefreshed:(NSNotification *)notification {
  838. // Retrieve the Instance ID default token, and if it is non-nil, post it
  839. NSString *token = self.instanceID.token;
  840. // Sometimes Instance ID doesn't yet have a token, so wait until the default
  841. // token is fetched, and then notify. This ensures that this token should not
  842. // be nil when the developer accesses it.
  843. if (token != nil) {
  844. NSString *oldToken = self.defaultFcmToken;
  845. self.defaultFcmToken = [token copy];
  846. if (self.defaultFcmToken && ![self.defaultFcmToken isEqualToString:oldToken]) {
  847. [self notifyDelegateOfFCMTokenAvailability];
  848. }
  849. NSNotificationCenter *center = [NSNotificationCenter defaultCenter];
  850. [center postNotificationName:FIRMessagingRegistrationTokenRefreshedNotification object:nil];
  851. }
  852. }
  853. #pragma mark - Application Support Directory
  854. + (BOOL)hasSubDirectory:(NSString *)subDirectoryName {
  855. NSString *subDirectoryPath = [self pathForSubDirectory:subDirectoryName];
  856. BOOL isDirectory;
  857. if (![[NSFileManager defaultManager] fileExistsAtPath:subDirectoryPath
  858. isDirectory:&isDirectory]) {
  859. return NO;
  860. } else if (!isDirectory) {
  861. return NO;
  862. }
  863. return YES;
  864. }
  865. + (NSString *)pathForSubDirectory:(NSString *)subDirectoryName {
  866. NSArray *directoryPaths =
  867. NSSearchPathForDirectoriesInDomains(FIRMessagingSupportedDirectory(), NSUserDomainMask, YES);
  868. NSString *dirPath = directoryPaths.lastObject;
  869. NSArray *components = @[ dirPath, subDirectoryName ];
  870. return [NSString pathWithComponents:components];
  871. }
  872. + (BOOL)createSubDirectory:(NSString *)subDirectoryName {
  873. NSString *subDirectoryPath = [self pathForSubDirectory:subDirectoryName];
  874. BOOL hasSubDirectory;
  875. if (![[NSFileManager defaultManager] fileExistsAtPath:subDirectoryPath
  876. isDirectory:&hasSubDirectory]) {
  877. NSError *error;
  878. [[NSFileManager defaultManager] createDirectoryAtPath:subDirectoryPath
  879. withIntermediateDirectories:YES
  880. attributes:nil
  881. error:&error];
  882. if (error) {
  883. FIRMessagingLoggerError(kFIRMessagingMessageCodeMessaging017,
  884. @"Cannot create directory %@, error: %@", subDirectoryPath, error);
  885. return NO;
  886. }
  887. } else {
  888. if (!hasSubDirectory) {
  889. FIRMessagingLoggerError(kFIRMessagingMessageCodeMessaging018,
  890. @"Found file instead of directory at %@", subDirectoryPath);
  891. return NO;
  892. }
  893. }
  894. return YES;
  895. }
  896. #pragma mark - Locales
  897. + (NSString *)currentLocale {
  898. NSArray *locales = [self firebaseLocales];
  899. NSArray *preferredLocalizations =
  900. [NSBundle preferredLocalizationsFromArray:locales
  901. forPreferences:[NSLocale preferredLanguages]];
  902. NSString *legalDocsLanguage = [preferredLocalizations firstObject];
  903. // Use en as the default language
  904. return legalDocsLanguage ? legalDocsLanguage : @"en";
  905. }
  906. + (NSArray *)firebaseLocales {
  907. NSMutableArray *locales = [NSMutableArray array];
  908. NSDictionary *localesMap = [self firebaselocalesMap];
  909. for (NSString *key in localesMap) {
  910. [locales addObjectsFromArray:localesMap[key]];
  911. }
  912. return locales;
  913. }
  914. + (NSDictionary *)firebaselocalesMap {
  915. return @{
  916. // Albanian
  917. @"sq" : @[ @"sq_AL" ],
  918. // Belarusian
  919. @"be" : @[ @"be_BY" ],
  920. // Bulgarian
  921. @"bg" : @[ @"bg_BG" ],
  922. // Catalan
  923. @"ca" : @[ @"ca", @"ca_ES" ],
  924. // Croatian
  925. @"hr" : @[ @"hr", @"hr_HR" ],
  926. // Czech
  927. @"cs" : @[ @"cs", @"cs_CZ" ],
  928. // Danish
  929. @"da" : @[ @"da", @"da_DK" ],
  930. // Estonian
  931. @"et" : @[ @"et_EE" ],
  932. // Finnish
  933. @"fi" : @[ @"fi", @"fi_FI" ],
  934. // Hebrew
  935. @"he" : @[ @"he", @"iw_IL" ],
  936. // Hindi
  937. @"hi" : @[ @"hi_IN" ],
  938. // Hungarian
  939. @"hu" : @[ @"hu", @"hu_HU" ],
  940. // Icelandic
  941. @"is" : @[ @"is_IS" ],
  942. // Indonesian
  943. @"id" : @[ @"id", @"in_ID", @"id_ID" ],
  944. // Irish
  945. @"ga" : @[ @"ga_IE" ],
  946. // Korean
  947. @"ko" : @[ @"ko", @"ko_KR", @"ko-KR" ],
  948. // Latvian
  949. @"lv" : @[ @"lv_LV" ],
  950. // Lithuanian
  951. @"lt" : @[ @"lt_LT" ],
  952. // Macedonian
  953. @"mk" : @[ @"mk_MK" ],
  954. // Malay
  955. @"ms" : @[ @"ms_MY" ],
  956. // Maltese
  957. @"ms" : @[ @"mt_MT" ],
  958. // Polish
  959. @"pl" : @[ @"pl", @"pl_PL", @"pl-PL" ],
  960. // Romanian
  961. @"ro" : @[ @"ro", @"ro_RO" ],
  962. // Russian
  963. @"ru" : @[ @"ru_RU", @"ru", @"ru_BY", @"ru_KZ", @"ru-RU" ],
  964. // Slovak
  965. @"sk" : @[ @"sk", @"sk_SK" ],
  966. // Slovenian
  967. @"sl" : @[ @"sl_SI" ],
  968. // Swedish
  969. @"sv" : @[ @"sv", @"sv_SE", @"sv-SE" ],
  970. // Turkish
  971. @"tr" : @[ @"tr", @"tr-TR", @"tr_TR" ],
  972. // Ukrainian
  973. @"uk" : @[ @"uk", @"uk_UA" ],
  974. // Vietnamese
  975. @"vi" : @[ @"vi", @"vi_VN" ],
  976. // The following are groups of locales or locales that sub-divide a
  977. // language).
  978. // Arabic
  979. @"ar" : @[
  980. @"ar", @"ar_DZ", @"ar_BH", @"ar_EG", @"ar_IQ", @"ar_JO", @"ar_KW",
  981. @"ar_LB", @"ar_LY", @"ar_MA", @"ar_OM", @"ar_QA", @"ar_SA", @"ar_SD",
  982. @"ar_SY", @"ar_TN", @"ar_AE", @"ar_YE", @"ar_GB", @"ar-IQ", @"ar_US"
  983. ],
  984. // Simplified Chinese
  985. @"zh_Hans" : @[ @"zh_CN", @"zh_SG", @"zh-Hans" ],
  986. // Traditional Chinese
  987. @"zh_Hant" : @[ @"zh_HK", @"zh_TW", @"zh-Hant", @"zh-HK", @"zh-TW" ],
  988. // Dutch
  989. @"nl" : @[ @"nl", @"nl_BE", @"nl_NL", @"nl-NL" ],
  990. // English
  991. @"en" : @[
  992. @"en", @"en_AU", @"en_CA", @"en_IN", @"en_IE", @"en_MT", @"en_NZ", @"en_PH",
  993. @"en_SG", @"en_ZA", @"en_GB", @"en_US", @"en_AE", @"en-AE", @"en_AS", @"en-AU",
  994. @"en_BD", @"en-CA", @"en_EG", @"en_ES", @"en_GB", @"en-GB", @"en_HK", @"en_ID",
  995. @"en-IN", @"en_NG", @"en-PH", @"en_PK", @"en-SG", @"en-US"
  996. ],
  997. // French
  998. @"fr" :
  999. @[ @"fr", @"fr_BE", @"fr_CA", @"fr_FR", @"fr_LU", @"fr_CH", @"fr-CA", @"fr-FR", @"fr_MA" ],
  1000. // German
  1001. @"de" : @[ @"de", @"de_AT", @"de_DE", @"de_LU", @"de_CH", @"de-DE" ],
  1002. // Greek
  1003. @"el" : @[ @"el", @"el_CY", @"el_GR" ],
  1004. // Italian
  1005. @"it" : @[ @"it", @"it_IT", @"it_CH", @"it-IT" ],
  1006. // Japanese
  1007. @"ja" : @[ @"ja", @"ja_JP", @"ja_JP_JP", @"ja-JP" ],
  1008. // Norwegian
  1009. @"no" : @[ @"nb", @"no_NO", @"no_NO_NY", @"nb_NO" ],
  1010. // Brazilian Portuguese
  1011. @"pt_BR" : @[ @"pt_BR", @"pt-BR" ],
  1012. // European Portuguese
  1013. @"pt_PT" : @[ @"pt", @"pt_PT", @"pt-PT" ],
  1014. // Serbian
  1015. @"sr" : @[ @"sr_BA", @"sr_ME", @"sr_RS", @"sr_Latn_BA", @"sr_Latn_ME", @"sr_Latn_RS" ],
  1016. // European Spanish
  1017. @"es_ES" : @[ @"es", @"es_ES", @"es-ES" ],
  1018. // Mexican Spanish
  1019. @"es_MX" : @[ @"es-MX", @"es_MX", @"es_US", @"es-US" ],
  1020. // Latin American Spanish
  1021. @"es_419" : @[
  1022. @"es_AR", @"es_BO", @"es_CL", @"es_CO", @"es_CR", @"es_DO", @"es_EC",
  1023. @"es_SV", @"es_GT", @"es_HN", @"es_NI", @"es_PA", @"es_PY", @"es_PE",
  1024. @"es_PR", @"es_UY", @"es_VE", @"es-AR", @"es-CL", @"es-CO"
  1025. ],
  1026. // Thai
  1027. @"th" : @[ @"th", @"th_TH", @"th_TH_TH" ],
  1028. };
  1029. }
  1030. @end