FIRMessaging.m 42 KB

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