FIRMessaging.m 38 KB

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