FIRMessaging.m 43 KB

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