FIRMessaging.m 43 KB

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