FIRMessaging.m 44 KB

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