FIRMessaging.m 42 KB

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