2 * Copyright 2017 Google
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
8 * http://www.apache.org/licenses/LICENSE-2.0
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.
17 #if !__has_feature(objc_arc)
18 #error FIRMessagingLib should be compiled with ARC.
21 #import "FIRMessaging.h"
22 #import "FIRMessaging_Private.h"
24 #import <UIKit/UIKit.h>
26 #import "FIRMessagingClient.h"
27 #import "FIRMessagingConstants.h"
28 #import "FIRMessagingContextManagerService.h"
29 #import "FIRMessagingDataMessageManager.h"
30 #import "FIRMessagingDefines.h"
31 #import "FIRMessagingLogger.h"
32 #import "FIRMessagingPubSub.h"
33 #import "FIRMessagingReceiver.h"
34 #import "FIRMessagingRemoteNotificationsProxy.h"
35 #import "FIRMessagingRmqManager.h"
36 #import "FIRMessagingSyncMessageManager.h"
37 #import "FIRMessagingUtilities.h"
38 #import "FIRMessagingVersionUtilities.h"
39 #import "FIRMessaging_Private.h"
41 #import <FirebaseCore/FIRAppInternal.h>
42 #import <FirebaseInstanceID/FirebaseInstanceID.h>
43 #import <GoogleUtilities/GULReachabilityChecker.h>
45 #import "NSError+FIRMessaging.h"
47 static NSString *const kFIRMessagingMessageViaAPNSRootKey = @"aps";
48 static NSString *const kFIRMessagingReachabilityHostname = @"www.google.com";
49 static NSString *const kFIRMessagingDefaultTokenScope = @"*";
50 static NSString *const kFIRMessagingFCMTokenFetchAPNSOption = @"apns_token";
52 #if defined(__IPHONE_10_0) && __IPHONE_OS_VERSION_MAX_ALLOWED >= __IPHONE_10_0
53 const NSNotificationName FIRMessagingSendSuccessNotification =
54 @"com.firebase.messaging.notif.send-success";
55 const NSNotificationName FIRMessagingSendErrorNotification =
56 @"com.firebase.messaging.notif.send-error";
57 const NSNotificationName FIRMessagingMessagesDeletedNotification =
58 @"com.firebase.messaging.notif.messages-deleted";
59 const NSNotificationName FIRMessagingConnectionStateChangedNotification =
60 @"com.firebase.messaging.notif.connection-state-changed";
61 const NSNotificationName FIRMessagingRegistrationTokenRefreshedNotification =
62 @"com.firebase.messaging.notif.fcm-token-refreshed";
64 NSString *const FIRMessagingSendSuccessNotification =
65 @"com.firebase.messaging.notif.send-success";
66 NSString *const FIRMessagingSendErrorNotification =
67 @"com.firebase.messaging.notif.send-error";
68 NSString * const FIRMessagingMessagesDeletedNotification =
69 @"com.firebase.messaging.notif.messages-deleted";
70 NSString * const FIRMessagingConnectionStateChangedNotification =
71 @"com.firebase.messaging.notif.connection-state-changed";
72 NSString * const FIRMessagingRegistrationTokenRefreshedNotification =
73 @"com.firebase.messaging.notif.fcm-token-refreshed";
74 #endif // defined(__IPHONE_10_0) && __IPHONE_OS_VERSION_MAX_ALLOWED >= __IPHONE_10_0
76 NSString *const kFIRMessagingUserDefaultsKeyAutoInitEnabled =
77 @"com.firebase.messaging.auto-init.enabled"; // Auto Init Enabled key stored in NSUserDefaults
79 NSString *const kFIRMessagingAPNSTokenType = @"APNSTokenType"; // APNS Token type key stored in user info.
81 NSString *const kFIRMessagingPlistAutoInitEnabled =
82 @"FirebaseMessagingAutoInitEnabled"; // Auto Init Enabled key stored in Info.plist
84 @interface FIRMessagingMessageInfo ()
86 @property(nonatomic, readwrite, assign) FIRMessagingMessageStatus status;
90 @implementation FIRMessagingMessageInfo
92 - (instancetype)init {
93 FIRMessagingInvalidateInitializer();
96 - (instancetype)initWithStatus:(FIRMessagingMessageStatus)status {
106 #pragma mark - for iOS 10 compatibility
107 @implementation FIRMessagingRemoteMessage
109 - (instancetype)init {
112 _appData = [[NSMutableDictionary alloc] init];
118 - (instancetype)initWithMessage:(FIRMessagingRemoteMessage *)message {
121 _appData = [message.appData copy];
129 @interface FIRMessaging ()<FIRMessagingClientDelegate, FIRMessagingReceiverDelegate,
130 GULReachabilityDelegate>
133 @property(nonatomic, readwrite, strong) NSData *apnsTokenData;
134 @property(nonatomic, readwrite, strong) NSString *defaultFcmToken;
136 @property(nonatomic, readwrite, strong) FIRInstanceID *instanceID;
138 @property(nonatomic, readwrite, assign) BOOL isClientSetup;
140 @property(nonatomic, readwrite, strong) FIRMessagingClient *client;
141 @property(nonatomic, readwrite, strong) GULReachabilityChecker *reachability;
142 @property(nonatomic, readwrite, strong) FIRMessagingDataMessageManager *dataMessageManager;
143 @property(nonatomic, readwrite, strong) FIRMessagingPubSub *pubsub;
144 @property(nonatomic, readwrite, strong) FIRMessagingRmqManager *rmq2Manager;
145 @property(nonatomic, readwrite, strong) FIRMessagingReceiver *receiver;
146 @property(nonatomic, readwrite, strong) FIRMessagingSyncMessageManager *syncMessageManager;
147 @property(nonatomic, readwrite, strong) NSUserDefaults *messagingUserDefaults;
149 /// Message ID's logged for analytics. This prevents us from logging the same message twice
150 /// which can happen if the user inadvertently calls `appDidReceiveMessage` along with us
151 /// calling it implicitly during swizzling.
152 @property(nonatomic, readwrite, strong) NSMutableSet *loggedMessageIDs;
154 - (instancetype)initWithInstanceID:(FIRInstanceID *)instanceID
155 userDefaults:(NSUserDefaults *)defaults NS_DESIGNATED_INITIALIZER;
159 @implementation FIRMessaging
161 + (FIRMessaging *)messaging {
162 static FIRMessaging *messaging;
163 static dispatch_once_t onceToken;
164 dispatch_once(&onceToken, ^{
165 messaging = [[FIRMessaging alloc] initPrivately];
171 - (instancetype)initWithInstanceID:(FIRInstanceID *)instanceID
172 userDefaults:(NSUserDefaults *)defaults {
175 _loggedMessageIDs = [NSMutableSet set];
176 _instanceID = instanceID;
177 _messagingUserDefaults = defaults;
182 - (instancetype)initPrivately {
183 return [self initWithInstanceID:[FIRInstanceID instanceID]
184 userDefaults:[NSUserDefaults standardUserDefaults]];
188 [self.reachability stop];
189 [[NSNotificationCenter defaultCenter] removeObserver:self];
193 #pragma mark - Config
196 [[NSNotificationCenter defaultCenter] addObserver:self
197 selector:@selector(didReceiveConfigureSDKNotification:)
198 name:kFIRAppReadyToConfigureSDKNotification
202 + (void)didReceiveConfigureSDKNotification:(NSNotification *)notification {
203 NSDictionary *appInfoDict = notification.userInfo;
204 NSNumber *isDefaultApp = appInfoDict[kFIRAppIsDefaultAppKey];
205 if (![isDefaultApp boolValue]) {
206 // Only configure for the default FIRApp.
207 FIRMessagingLoggerDebug(kFIRMessagingMessageCodeFIRApp001,
208 @"Firebase Messaging only works with the default app.");
212 NSString *appName = appInfoDict[kFIRAppNameKey];
213 FIRApp *app = [FIRApp appNamed:appName];
214 [[FIRMessaging messaging] configureMessaging:app];
217 - (void)configureMessaging:(FIRApp *)app {
218 // Swizzle remote-notification-related methods (app delegate and UNUserNotificationCenter)
219 if ([FIRMessagingRemoteNotificationsProxy canSwizzleMethods]) {
220 NSString *docsURLString = @"https://firebase.google.com/docs/cloud-messaging/ios/client"
221 @"#method_swizzling_in_firebase_messaging";
222 FIRMessagingLoggerNotice(kFIRMessagingMessageCodeFIRApp000,
223 @"FIRMessaging Remote Notifications proxy enabled, will swizzle "
224 @"remote notification receiver handlers. If you'd prefer to manually "
225 @"integrate Firebase Messaging, add \"%@\" to your Info.plist, "
226 @"and set it to NO. Follow the instructions at:\n%@\nto ensure "
227 @"proper integration.",
228 kFIRMessagingRemoteNotificationsProxyEnabledInfoPlistKey,
230 [FIRMessagingRemoteNotificationsProxy swizzleMethods];
235 // Print the library version for logging.
236 NSString *currentLibraryVersion = FIRMessagingCurrentLibraryVersion();
237 FIRMessagingLoggerInfo(kFIRMessagingMessageCodeMessagingPrintLibraryVersion,
238 @"FIRMessaging library version %@",
239 currentLibraryVersion);
241 [self setupReceiver];
243 NSString *hostname = kFIRMessagingReachabilityHostname;
244 self.reachability = [[GULReachabilityChecker alloc] initWithReachabilityDelegate:self
246 [self.reachability start];
248 [self setupApplicationSupportSubDirectory];
249 // setup FIRMessaging objects
250 [self setupRmqManager];
252 [self setupSyncMessageManager];
253 [self setupDataMessageManager];
256 self.isClientSetup = YES;
257 [self setupNotificationListeners];
260 - (void)setupApplicationSupportSubDirectory {
261 NSString *messagingSubDirectory = kFIRMessagingApplicationSupportSubDirectory;
262 if (![[self class] hasApplicationSupportSubDirectory:messagingSubDirectory]) {
263 [[self class] createApplicationSupportSubDirectory:messagingSubDirectory];
267 - (void)setupNotificationListeners {
268 // To prevent multiple notifications remove self as observer for all events.
269 NSNotificationCenter *center = [NSNotificationCenter defaultCenter];
270 [center removeObserver:self];
272 [center addObserver:self
273 selector:@selector(didReceiveDefaultInstanceIDToken:)
274 name:kFIRMessagingFCMTokenNotification
276 [center addObserver:self
277 selector:@selector(defaultInstanceIDTokenWasRefreshed:)
278 name:kFIRMessagingRegistrationTokenRefreshNotification
280 [center addObserver:self
281 selector:@selector(applicationStateChanged)
282 name:UIApplicationDidBecomeActiveNotification
284 [center addObserver:self
285 selector:@selector(applicationStateChanged)
286 name:UIApplicationDidEnterBackgroundNotification
290 - (void)setupReceiver {
291 self.receiver = [[FIRMessagingReceiver alloc] init];
292 self.receiver.delegate = self;
295 - (void)setupClient {
296 self.client = [[FIRMessagingClient alloc] initWithDelegate:self
297 reachability:self.reachability
298 rmq2Manager:self.rmq2Manager];
301 - (void)setupDataMessageManager {
302 self.dataMessageManager =
303 [[FIRMessagingDataMessageManager alloc] initWithDelegate:self.receiver
305 rmq2Manager:self.rmq2Manager
306 syncMessageManager:self.syncMessageManager];
308 [self.dataMessageManager refreshDelayedMessages];
309 [self.client setDataMessageManager:self.dataMessageManager];
312 - (void)setupRmqManager {
313 self.rmq2Manager = [[FIRMessagingRmqManager alloc] initWithDatabaseName:@"rmq2"];
314 [self.rmq2Manager loadRmqId];
317 - (void)setupTopics {
318 _FIRMessagingDevAssert(self.client, @"Invalid nil client before init pubsub.");
319 self.pubsub = [[FIRMessagingPubSub alloc] initWithClient:self.client];
322 - (void)setupSyncMessageManager {
323 self.syncMessageManager =
324 [[FIRMessagingSyncMessageManager alloc] initWithRmqManager:self.rmq2Manager];
326 // Delete the expired messages with a delay. We don't want to block startup with a somewhat
327 // expensive db call.
328 FIRMessaging_WEAKIFY(self);
329 dispatch_time_t time = dispatch_time(DISPATCH_TIME_NOW, (int64_t)(5.0 * NSEC_PER_SEC));
330 dispatch_after(time, dispatch_get_main_queue(), ^{
331 FIRMessaging_STRONGIFY(self);
332 [self.syncMessageManager removeExpiredSyncMessages];
337 _FIRMessagingDevAssert([NSThread isMainThread],
338 @"FIRMessaging should be called from main thread only.");
339 [self.client teardown];
341 self.syncMessageManager = nil;
342 self.rmq2Manager = nil;
343 self.dataMessageManager = nil;
345 self.isClientSetup = NO;
346 FIRMessagingLoggerDebug(kFIRMessagingMessageCodeMessaging001, @"Did successfully teardown");
349 #pragma mark - Messages
351 - (FIRMessagingMessageInfo *)appDidReceiveMessage:(NSDictionary *)message {
352 if (!message.count) {
353 return [[FIRMessagingMessageInfo alloc] initWithStatus:FIRMessagingMessageStatusUnknown];
356 // For downstream messages that go via MCS we should strip out this key before sending
357 // the message to the device.
358 BOOL isOldMessage = NO;
359 NSString *messageID = message[kFIRMessagingMessageIDKey];
360 if ([messageID length]) {
361 [self.rmq2Manager saveS2dMessageWithRmqId:messageID];
363 BOOL isSyncMessage = [[self class] isAPNSSyncMessage:message];
365 isOldMessage = [self.syncMessageManager didReceiveAPNSSyncMessage:message];
368 // Prevent duplicates by keeping a cache of all the logged messages during each session.
369 // The duplicates only happen when the 3P app calls `appDidReceiveMessage:` along with
370 // us swizzling their implementation to call the same method implicitly.
371 if (!isOldMessage && messageID.length) {
372 isOldMessage = [self.loggedMessageIDs containsObject:messageID];
374 [self.loggedMessageIDs addObject:messageID];
379 Class firMessagingLogClass = NSClassFromString(@"FIRMessagingLog");
380 SEL logMessageSelector = NSSelectorFromString(@"logMessage:");
382 if ([firMessagingLogClass respondsToSelector:logMessageSelector]) {
383 #pragma clang diagnostic push
384 #pragma clang diagnostic ignored "-Warc-performSelector-leaks"
385 [firMessagingLogClass performSelector:logMessageSelector
388 #pragma clang diagnostic pop
389 [self handleContextManagerMessage:message];
390 [self handleIncomingLinkIfNeededFromMessage:message];
392 return [[FIRMessagingMessageInfo alloc] initWithStatus:FIRMessagingMessageStatusNew];
395 - (BOOL)handleContextManagerMessage:(NSDictionary *)message {
396 if ([FIRMessagingContextManagerService isContextManagerMessage:message]) {
397 return [FIRMessagingContextManagerService handleContextManagerMessage:message];
402 + (BOOL)isAPNSSyncMessage:(NSDictionary *)message {
403 if ([message[kFIRMessagingMessageViaAPNSRootKey] isKindOfClass:[NSDictionary class]]) {
404 NSDictionary *aps = message[kFIRMessagingMessageViaAPNSRootKey];
405 return [aps[kFIRMessagingMessageAPNSContentAvailableKey] boolValue];
410 - (void)handleIncomingLinkIfNeededFromMessage:(NSDictionary *)message {
411 NSURL *url = [self linkURLFromMessage:message];
415 if (![NSThread isMainThread]) {
416 dispatch_async(dispatch_get_main_queue(), ^{
417 [self handleIncomingLinkIfNeededFromMessage:message];
422 UIApplication *application = FIRMessagingUIApplication();
426 id<UIApplicationDelegate> appDelegate = application.delegate;
427 SEL continueUserActivitySelector =
428 @selector(application:continueUserActivity:restorationHandler:);
429 SEL openURLWithOptionsSelector = @selector(application:openURL:options:);
430 SEL openURLWithSourceApplicationSelector =
431 @selector(application:openURL:sourceApplication:annotation:);
432 SEL handleOpenURLSelector = @selector(application:handleOpenURL:);
433 // Due to FIRAAppDelegateProxy swizzling, this selector will most likely get chosen, whether or
434 // not the actual application has implemented
435 // |application:continueUserActivity:restorationHandler:|. A warning will be displayed to the user
436 // if they haven't implemented it.
437 if ([NSUserActivity class] != nil &&
438 [appDelegate respondsToSelector:continueUserActivitySelector]) {
439 NSUserActivity *userActivity =
440 [[NSUserActivity alloc] initWithActivityType:NSUserActivityTypeBrowsingWeb];
441 userActivity.webpageURL = url;
442 [appDelegate application:application
443 continueUserActivity:userActivity
444 restorationHandler:^(NSArray * _Nullable restorableObjects) {
445 // Do nothing, as we don't support the app calling this block
448 } else if ([appDelegate respondsToSelector:openURLWithOptionsSelector]) {
449 #pragma clang diagnostic push
450 #pragma clang diagnostic ignored "-Wunguarded-availability"
451 [appDelegate application:application openURL:url options:@{}];
452 #pragma clang diagnostic pop
454 // Similarly, |application:openURL:sourceApplication:annotation:| will also always be called, due
455 // to the default swizzling done by FIRAAppDelegateProxy in Firebase Analytics
456 } else if ([appDelegate respondsToSelector:openURLWithSourceApplicationSelector]) {
457 #pragma clang diagnostic push
458 #pragma clang diagnostic ignored "-Wdeprecated-declarations"
459 [appDelegate application:application
461 sourceApplication:FIRMessagingAppIdentifier()
463 } else if ([appDelegate respondsToSelector:handleOpenURLSelector]) {
464 [appDelegate application:application handleOpenURL:url];
465 #pragma clang diagnostic pop
469 - (NSURL *)linkURLFromMessage:(NSDictionary *)message {
470 NSString *urlString = message[kFIRMessagingMessageLinkKey];
471 if (urlString == nil || ![urlString isKindOfClass:[NSString class]] || urlString.length == 0) {
474 NSURL *url = [NSURL URLWithString:urlString];
480 - (NSData *)APNSToken {
481 return self.apnsTokenData;
484 - (void)setAPNSToken:(NSData *)APNSToken {
485 [self setAPNSToken:APNSToken type:FIRMessagingAPNSTokenTypeUnknown];
488 - (void)setAPNSToken:(NSData *)apnsToken type:(FIRMessagingAPNSTokenType)type {
489 if ([apnsToken isEqual:self.apnsTokenData]) {
492 self.apnsTokenData = apnsToken;
494 // Notify InstanceID that APNS Token has been set.
495 NSDictionary *userInfo = @{kFIRMessagingAPNSTokenType : @(type)};
496 NSNotification *notification =
497 [NSNotification notificationWithName:kFIRMessagingAPNSTokenNotification
498 object:[apnsToken copy]
500 [[NSNotificationQueue defaultQueue] enqueueNotification:notification postingStyle:NSPostASAP];
505 - (BOOL)isAutoInitEnabled {
507 id isAutoInitEnabledObject =
508 [_messagingUserDefaults objectForKey:kFIRMessagingUserDefaultsKeyAutoInitEnabled];
509 if (isAutoInitEnabledObject) {
510 return [isAutoInitEnabledObject boolValue];
514 isAutoInitEnabledObject =
515 [[NSBundle mainBundle] objectForInfoDictionaryKey:kFIRMessagingPlistAutoInitEnabled];
516 if (isAutoInitEnabledObject) {
517 return [isAutoInitEnabledObject boolValue];
520 // If none of above exists, we default to the global switch that comes from FIRApp.
521 return [[FIRApp defaultApp] isDataCollectionDefaultEnabled];
524 - (void)setAutoInitEnabled:(BOOL)autoInitEnabled {
525 BOOL isFCMAutoInitEnabled = [self isAutoInitEnabled];
526 [_messagingUserDefaults setBool:autoInitEnabled
527 forKey:kFIRMessagingUserDefaultsKeyAutoInitEnabled];
528 [_messagingUserDefaults synchronize];
529 if (!isFCMAutoInitEnabled && autoInitEnabled) {
530 #pragma clang diagnostic push
531 #pragma clang diagnostic ignored "-Wdeprecated-declarations"
532 self.defaultFcmToken = self.instanceID.token;
533 #pragma clang diagnostic pop
537 - (NSString *)FCMToken {
538 NSString *token = self.defaultFcmToken;
540 // We may not have received it from Instance ID yet (via NSNotification), so extract it directly
541 #pragma clang diagnostic push
542 #pragma clang diagnostic ignored "-Wdeprecated-declarations"
543 token = self.instanceID.token;
544 #pragma clang diagnostic pop
549 - (void)retrieveFCMTokenForSenderID:(nonnull NSString *)senderID
550 completion:(nonnull FIRMessagingFCMTokenFetchCompletion)completion {
551 if (!senderID.length) {
552 FIRMessagingLoggerError(kFIRMessagingMessageCodeSenderIDNotSuppliedForTokenFetch,
553 @"Sender ID not supplied. It is required for a token fetch, "
554 @"to identify the sender.");
556 NSString *description = @"Couldn't fetch token because a Sender ID was not supplied. A valid "
557 @"Sender ID is required to fetch an FCM token";
558 NSError *error = [NSError fcm_errorWithCode:FIRMessagingErrorInvalidRequest
559 userInfo:@{NSLocalizedDescriptionKey : description}];
560 completion(nil, error);
564 NSDictionary *options = nil;
565 if (self.APNSToken) {
566 options = @{kFIRMessagingFCMTokenFetchAPNSOption : self.APNSToken};
568 FIRMessagingLoggerWarn(kFIRMessagingMessageCodeAPNSTokenNotAvailableDuringTokenFetch,
569 @"APNS device token not set before retrieving FCM Token for Sender ID "
570 @"'%@'. Notifications to this FCM Token will not be delivered over APNS."
571 @"Be sure to re-retrieve the FCM token once the APNS device token is "
574 [self.instanceID tokenWithAuthorizedEntity:senderID
575 scope:kFIRMessagingDefaultTokenScope
580 - (void)deleteFCMTokenForSenderID:(nonnull NSString *)senderID
581 completion:(nonnull FIRMessagingDeleteFCMTokenCompletion)completion {
582 if (!senderID.length) {
583 FIRMessagingLoggerError(kFIRMessagingMessageCodeSenderIDNotSuppliedForTokenDelete,
584 @"Sender ID not supplied. It is required to delete an FCM token.");
586 NSString *description = @"Couldn't delete token because a Sender ID was not supplied. A "
587 @"valid Sender ID is required to delete an FCM token";
588 NSError *error = [NSError fcm_errorWithCode:FIRMessagingErrorInvalidRequest
589 userInfo:@{NSLocalizedDescriptionKey : description}];
594 [self.instanceID deleteTokenWithAuthorizedEntity:senderID
595 scope:kFIRMessagingDefaultTokenScope
599 #pragma mark - FIRMessagingDelegate helper methods
600 - (void)setDelegate:(id<FIRMessagingDelegate>)delegate {
601 _delegate = delegate;
602 [self validateDelegateConformsToTokenAvailabilityMethods];
605 // Check if the delegate conforms to |didReceiveRegistrationToken:|
606 // and display a warning to the developer if not.
607 // NOTE: Once |didReceiveRegistrationToken:| can be made a required method, this
608 // check can be removed.
609 - (void)validateDelegateConformsToTokenAvailabilityMethods {
611 ![self.delegate respondsToSelector:@selector(messaging:didReceiveRegistrationToken:)]) {
612 FIRMessagingLoggerWarn(kFIRMessagingMessageCodeTokenDelegateMethodsNotImplemented,
613 @"The object %@ does not respond to "
614 @"-messaging:didReceiveRegistrationToken:. Please implement "
615 @"-messaging:didReceiveRegistrationToken: to be provided with an FCM "
616 @"token.", self.delegate.description);
620 - (void)notifyDelegateOfFCMTokenAvailability {
621 __weak FIRMessaging *weakSelf = self;
622 if (![NSThread isMainThread]) {
623 dispatch_async(dispatch_get_main_queue(), ^{
624 [weakSelf notifyDelegateOfFCMTokenAvailability];
628 if ([self.delegate respondsToSelector:@selector(messaging:didReceiveRegistrationToken:)]) {
629 [self.delegate messaging:self didReceiveRegistrationToken:self.defaultFcmToken];
633 #pragma mark - Application State Changes
635 - (void)applicationStateChanged {
636 if (self.shouldEstablishDirectChannel) {
637 [self updateAutomaticClientConnection];
641 #pragma mark - Direct Channel
643 - (void)setShouldEstablishDirectChannel:(BOOL)shouldEstablishDirectChannel {
644 if (_shouldEstablishDirectChannel == shouldEstablishDirectChannel) {
647 _shouldEstablishDirectChannel = shouldEstablishDirectChannel;
648 [self updateAutomaticClientConnection];
651 - (BOOL)isDirectChannelEstablished {
652 return self.client.isConnectionActive;
655 - (BOOL)shouldBeConnectedAutomatically {
656 // We require a token from Instance ID
657 NSString *token = self.defaultFcmToken;
658 // Only on foreground connections
659 UIApplication *application = FIRMessagingUIApplication();
663 UIApplicationState applicationState = application.applicationState;
664 BOOL shouldBeConnected = _shouldEstablishDirectChannel &&
665 (token.length > 0) &&
666 applicationState == UIApplicationStateActive;
667 return shouldBeConnected;
670 - (void)updateAutomaticClientConnection {
671 if (![NSThread isMainThread]) {
672 // Call this method from the main thread
673 dispatch_async(dispatch_get_main_queue(), ^{
674 [self updateAutomaticClientConnection];
678 BOOL shouldBeConnected = [self shouldBeConnectedAutomatically];
679 if (shouldBeConnected && !self.client.isConnected) {
680 [self.client connectWithHandler:^(NSError *error) {
682 // It means we connected. Fire connection change notification
683 [self notifyOfDirectChannelConnectionChange];
686 } else if (!shouldBeConnected && self.client.isConnected) {
687 [self.client disconnect];
688 [self notifyOfDirectChannelConnectionChange];
692 - (void)notifyOfDirectChannelConnectionChange {
693 NSNotificationCenter *center = [NSNotificationCenter defaultCenter];
694 [center postNotificationName:FIRMessagingConnectionStateChangedNotification object:self];
697 #pragma mark - Connect
699 - (void)connectWithCompletion:(FIRMessagingConnectCompletion)handler {
700 _FIRMessagingDevAssert([NSThread isMainThread],
701 @"FIRMessaging connect should be called from main thread only.");
702 _FIRMessagingDevAssert(self.isClientSetup, @"FIRMessaging client not setup.");
703 [self.client connectWithHandler:^(NSError *error) {
708 // It means we connected. Fire connection change notification
709 [self notifyOfDirectChannelConnectionChange];
716 _FIRMessagingDevAssert([NSThread isMainThread],
717 @"FIRMessaging should be called from main thread only.");
718 if ([self.client isConnected]) {
719 [self.client disconnect];
720 [self notifyOfDirectChannelConnectionChange];
724 #pragma mark - Topics
726 + (NSString *)normalizeTopic:(NSString *)topic {
730 if (![FIRMessagingPubSub hasTopicsPrefix:topic]) {
731 topic = [FIRMessagingPubSub addPrefixToTopic:topic];
733 if ([FIRMessagingPubSub isValidTopicWithPrefix:topic]) {
739 - (void)subscribeToTopic:(NSString *)topic {
740 [self subscribeToTopic:topic completion:nil];
743 - (void)subscribeToTopic:(NSString *)topic
744 completion:(nullable FIRMessagingTopicOperationCompletion)completion {
745 if ([FIRMessagingPubSub hasTopicsPrefix:topic]) {
746 FIRMessagingLoggerWarn(kFIRMessagingMessageCodeTopicFormatIsDeprecated,
747 @"Format '%@' is deprecated. Only '%@' should be used in "
748 @"subscribeToTopic.",
749 topic, [FIRMessagingPubSub removePrefixFromTopic:topic]);
751 if (!self.defaultFcmToken.length) {
752 FIRMessagingLoggerWarn(kFIRMessagingMessageCodeMessaging010,
753 @"The subscription operation is suspended because you don't have a "
754 @"token. The operation will resume once you get an FCM token.");
756 NSString *normalizeTopic = [[self class] normalizeTopic:topic];
757 if (normalizeTopic.length) {
758 [self.pubsub subscribeToTopic:normalizeTopic handler:completion];
761 FIRMessagingLoggerError(kFIRMessagingMessageCodeMessaging009,
762 @"Cannot parse topic name %@. Will not subscribe.", topic);
765 - (void)unsubscribeFromTopic:(NSString *)topic {
766 [self unsubscribeFromTopic:topic completion:nil];
769 - (void)unsubscribeFromTopic:(NSString *)topic
770 completion:(nullable FIRMessagingTopicOperationCompletion)completion {
771 if ([FIRMessagingPubSub hasTopicsPrefix:topic]) {
772 FIRMessagingLoggerWarn(kFIRMessagingMessageCodeTopicFormatIsDeprecated,
773 @"Format '%@' is deprecated. Only '%@' should be used in "
774 @"unsubscribeFromTopic.",
775 topic, [FIRMessagingPubSub removePrefixFromTopic:topic]);
777 if (!self.defaultFcmToken.length) {
778 FIRMessagingLoggerWarn(kFIRMessagingMessageCodeMessaging012,
779 @"The unsubscription operation is suspended because you don't have a "
780 @"token. The operation will resume once you get an FCM token.");
782 NSString *normalizeTopic = [[self class] normalizeTopic:topic];
783 if (normalizeTopic.length) {
784 [self.pubsub unsubscribeFromTopic:normalizeTopic handler:completion];
787 FIRMessagingLoggerError(kFIRMessagingMessageCodeMessaging011,
788 @"Cannot parse topic name %@. Will not unsubscribe.", topic);
793 - (void)sendMessage:(NSDictionary *)message
795 withMessageID:(NSString *)messageID
796 timeToLive:(int64_t)ttl {
797 _FIRMessagingDevAssert([to length] != 0, @"Invalid receiver id for FIRMessaging-message");
799 NSMutableDictionary *fcmMessage = [[self class] createFIRMessagingMessageWithMessage:message
804 FIRMessagingLoggerInfo(kFIRMessagingMessageCodeMessaging013, @"Sending message: %@ with id: %@",
806 [self.dataMessageManager sendDataMessageStanza:fcmMessage];
809 + (NSMutableDictionary *)createFIRMessagingMessageWithMessage:(NSDictionary *)message
811 withID:(NSString *)msgID
812 timeToLive:(int64_t)ttl
814 NSMutableDictionary *fcmMessage = [NSMutableDictionary dictionary];
815 fcmMessage[kFIRMessagingSendTo] = [to copy];
816 fcmMessage[kFIRMessagingSendMessageID] = msgID ? [msgID copy] : @"";
817 fcmMessage[kFIRMessagingSendTTL] = @(ttl);
818 fcmMessage[kFIRMessagingSendDelay] = @(delay);
819 fcmMessage[KFIRMessagingSendMessageAppData] =
820 [NSMutableDictionary dictionaryWithDictionary:message];
824 #pragma mark - IID dependencies
826 + (NSString *)FIRMessagingSDKVersion {
827 return FIRMessagingCurrentLibraryVersion();
830 + (NSString *)FIRMessagingSDKCurrentLocale {
831 return [self currentLocale];
834 #pragma mark - FIRMessagingReceiverDelegate
836 - (void)receiver:(FIRMessagingReceiver *)receiver
837 receivedRemoteMessage:(FIRMessagingRemoteMessage *)remoteMessage {
838 if ([self.delegate respondsToSelector:@selector(messaging:didReceiveMessage:)]) {
839 #pragma clang diagnostic push
840 #pragma clang diagnostic ignored "-Wunguarded-availability"
841 [self.delegate messaging:self didReceiveMessage:remoteMessage];
844 // Delegate methods weren't implemented, so messages are being dropped, log a warning
845 FIRMessagingLoggerWarn(kFIRMessagingMessageCodeRemoteMessageDelegateMethodNotImplemented,
846 @"FIRMessaging received data-message, but FIRMessagingDelegate's"
847 @"-messaging:didReceiveMessage: not implemented");
851 #pragma mark - GULReachabilityDelegate
853 - (void)reachability:(GULReachabilityChecker *)reachability
854 statusChanged:(GULReachabilityStatus)status {
855 [self onNetworkStatusChanged];
858 #pragma mark - Network
860 - (void)onNetworkStatusChanged {
861 if (![self.client isConnected] && [self isNetworkAvailable]) {
862 if (self.client.shouldStayConnected) {
863 FIRMessagingLoggerDebug(kFIRMessagingMessageCodeMessaging014,
864 @"Attempting to establish direct channel.");
865 [self.client retryConnectionImmediately:YES];
867 [self.pubsub scheduleSync:YES];
871 - (BOOL)isNetworkAvailable {
872 GULReachabilityStatus status = self.reachability.reachabilityStatus;
873 return (status == kGULReachabilityViaCellular || status == kGULReachabilityViaWifi);
876 - (FIRMessagingNetworkStatus)networkType {
877 GULReachabilityStatus status = self.reachability.reachabilityStatus;
878 if (![self isNetworkAvailable]) {
879 return kFIRMessagingReachabilityNotReachable;
880 } else if (status == kGULReachabilityViaCellular) {
881 return kFIRMessagingReachabilityReachableViaWWAN;
883 return kFIRMessagingReachabilityReachableViaWiFi;
887 #pragma mark - Notifications
889 - (void)didReceiveDefaultInstanceIDToken:(NSNotification *)notification {
890 if (notification.object && ![notification.object isKindOfClass:[NSString class]]) {
891 FIRMessagingLoggerDebug(kFIRMessagingMessageCodeMessaging015,
892 @"Invalid default FCM token type %@",
893 NSStringFromClass([notification.object class]));
896 NSString *oldToken = self.defaultFcmToken;
897 self.defaultFcmToken = [(NSString *)notification.object copy];
898 if (self.defaultFcmToken && ![self.defaultFcmToken isEqualToString:oldToken]) {
899 [self notifyDelegateOfFCMTokenAvailability];
901 [self.pubsub scheduleSync:YES];
902 if (self.shouldEstablishDirectChannel) {
903 [self updateAutomaticClientConnection];
907 - (void)defaultInstanceIDTokenWasRefreshed:(NSNotification *)notification {
908 // Retrieve the Instance ID default token, and if it is non-nil, post it
909 #pragma clang diagnostic push
910 #pragma clang diagnostic ignored "-Wdeprecated-declarations"
911 NSString *token = self.instanceID.token;
912 #pragma clang diagnostic pop
913 // Sometimes Instance ID doesn't yet have a token, so wait until the default
914 // token is fetched, and then notify. This ensures that this token should not
915 // be nil when the developer accesses it.
917 NSString *oldToken = self.defaultFcmToken;
918 self.defaultFcmToken = [token copy];
919 if (self.defaultFcmToken && ![self.defaultFcmToken isEqualToString:oldToken]) {
920 [self notifyDelegateOfFCMTokenAvailability];
922 NSNotificationCenter *center = [NSNotificationCenter defaultCenter];
923 [center postNotificationName:FIRMessagingRegistrationTokenRefreshedNotification object:nil];
927 #pragma mark - Application Support Directory
929 + (BOOL)hasApplicationSupportSubDirectory:(NSString *)subDirectoryName {
930 NSString *subDirectoryPath = [self pathForApplicationSupportSubDirectory:subDirectoryName];
932 if (![[NSFileManager defaultManager] fileExistsAtPath:subDirectoryPath
933 isDirectory:&isDirectory]) {
935 } else if (!isDirectory) {
941 + (NSString *)pathForApplicationSupportSubDirectory:(NSString *)subDirectoryName {
942 NSArray *directoryPaths = NSSearchPathForDirectoriesInDomains(NSApplicationSupportDirectory,
943 NSUserDomainMask, YES);
944 NSString *applicationSupportDirPath = directoryPaths.lastObject;
945 NSArray *components = @[applicationSupportDirPath, subDirectoryName];
946 return [NSString pathWithComponents:components];
949 + (BOOL)createApplicationSupportSubDirectory:(NSString *)subDirectoryName {
950 NSString *subDirectoryPath = [self pathForApplicationSupportSubDirectory:subDirectoryName];
951 BOOL hasSubDirectory;
953 if (![[NSFileManager defaultManager] fileExistsAtPath:subDirectoryPath
954 isDirectory:&hasSubDirectory]) {
956 [[NSFileManager defaultManager] createDirectoryAtPath:subDirectoryPath
957 withIntermediateDirectories:YES
961 FIRMessagingLoggerError(kFIRMessagingMessageCodeMessaging017,
962 @"Cannot create directory %@, error: %@", subDirectoryPath, error);
966 if (!hasSubDirectory) {
967 FIRMessagingLoggerError(kFIRMessagingMessageCodeMessaging018,
968 @"Found file instead of directory at %@", subDirectoryPath);
975 #pragma mark - Locales
977 + (NSString *)currentLocale {
978 NSArray *locales = [self firebaseLocales];
979 NSArray *preferredLocalizations =
980 [NSBundle preferredLocalizationsFromArray:locales
981 forPreferences:[NSLocale preferredLanguages]];
982 NSString *legalDocsLanguage = [preferredLocalizations firstObject];
983 // Use en as the default language
984 return legalDocsLanguage ? legalDocsLanguage : @"en";
987 + (NSArray *)firebaseLocales {
988 NSMutableArray *locales = [NSMutableArray array];
989 NSDictionary *localesMap = [self firebaselocalesMap];
990 for (NSString *key in localesMap) {
991 [locales addObjectsFromArray:localesMap[key]];
996 + (NSDictionary *)firebaselocalesMap {
999 @"sq" : @[ @"sq_AL" ],
1001 @"be" : @[ @"be_BY" ],
1003 @"bg" : @[ @"bg_BG" ],
1005 @"ca" : @[ @"ca", @"ca_ES" ],
1007 @"hr" : @[ @"hr", @"hr_HR" ],
1009 @"cs" : @[ @"cs", @"cs_CZ" ],
1011 @"da" : @[ @"da", @"da_DK" ],
1013 @"et" : @[ @"et_EE" ],
1015 @"fi" : @[ @"fi", @"fi_FI" ],
1017 @"he" : @[ @"he", @"iw_IL" ],
1019 @"hi" : @[ @"hi_IN" ],
1021 @"hu" : @[ @"hu", @"hu_HU" ],
1023 @"is" : @[ @"is_IS" ],
1025 @"id" : @[ @"id", @"in_ID", @"id_ID" ],
1027 @"ga" : @[ @"ga_IE" ],
1029 @"ko" : @[ @"ko", @"ko_KR", @"ko-KR" ],
1031 @"lv" : @[ @"lv_LV" ],
1033 @"lt" : @[ @"lt_LT" ],
1035 @"mk" : @[ @"mk_MK" ],
1037 @"ms" : @[ @"ms_MY" ],
1039 @"ms" : @[ @"mt_MT" ],
1041 @"pl" : @[ @"pl", @"pl_PL", @"pl-PL" ],
1043 @"ro" : @[ @"ro", @"ro_RO" ],
1045 @"ru" : @[ @"ru_RU", @"ru", @"ru_BY", @"ru_KZ", @"ru-RU" ],
1047 @"sk" : @[ @"sk", @"sk_SK" ],
1049 @"sl" : @[ @"sl_SI" ],
1051 @"sv" : @[ @"sv", @"sv_SE", @"sv-SE" ],
1053 @"tr" : @[ @"tr", @"tr-TR", @"tr_TR" ],
1055 @"uk" : @[ @"uk", @"uk_UA" ],
1057 @"vi" : @[ @"vi", @"vi_VN" ],
1058 // The following are groups of locales or locales that sub-divide a
1084 // Simplified Chinese
1085 @"zh_Hans" : @[ @"zh_CN", @"zh_SG", @"zh-Hans" ],
1086 // Traditional Chinese
1087 @"zh_Hant" : @[ @"zh_HK", @"zh_TW", @"zh-Hant", @"zh-HK", @"zh-TW" ],
1089 @"nl" : @[ @"nl", @"nl_BE", @"nl_NL", @"nl-NL" ],
1137 @"de" : @[ @"de", @"de_AT", @"de_DE", @"de_LU", @"de_CH", @"de-DE" ],
1139 @"el" : @[ @"el", @"el_CY", @"el_GR" ],
1141 @"it" : @[ @"it", @"it_IT", @"it_CH", @"it-IT" ],
1143 @"ja" : @[ @"ja", @"ja_JP", @"ja_JP_JP", @"ja-JP" ],
1145 @"no" : @[ @"nb", @"no_NO", @"no_NO_NY", @"nb_NO" ],
1146 // Brazilian Portuguese
1147 @"pt_BR" : @[ @"pt_BR", @"pt-BR" ],
1148 // European Portuguese
1149 @"pt_PT" : @[ @"pt", @"pt_PT", @"pt-PT" ],
1160 @"es_ES" : @[ @"es", @"es_ES", @"es-ES" ],
1162 @"es_MX" : @[ @"es-MX", @"es_MX", @"es_US", @"es-US" ],
1163 // Latin American Spanish
1187 @"th" : @[ @"th", @"th_TH", @"th_TH_TH" ],