FIRMessaging.m 46 KB

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