FIRMessaging.m 42 KB

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