FIRMessaging.m 43 KB

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