FIRMessaging.m 42 KB

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