FIRMessaging.m 44 KB

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