FIRMessaging.m 40 KB

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