FIRMessaging.m 43 KB

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