FIRMessaging.m 38 KB

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