FIRMessagingReceiver.m 7.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194
  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. #import "FIRMessagingReceiver.h"
  17. #import <UIKit/UIKit.h>
  18. #import <GoogleUtilities/GULAppEnvironmentUtil.h>
  19. #import <GoogleUtilities/GULUserDefaults.h>
  20. #import "FIRMessaging.h"
  21. #import "FIRMessagingLogger.h"
  22. #import "FIRMessagingUtilities.h"
  23. #import "FIRMessaging_Private.h"
  24. static NSString *const kUpstreamMessageIDUserInfoKey = @"messageID";
  25. static NSString *const kUpstreamErrorUserInfoKey = @"error";
  26. /// "Should use Messaging delegate" key stored in NSUserDefaults
  27. NSString *const kFIRMessagingUserDefaultsKeyUseMessagingDelegate =
  28. @"com.firebase.messaging.useMessagingDelegate";
  29. /// "Should use Messaging Delegate" key stored in Info.plist
  30. NSString *const kFIRMessagingPlistUseMessagingDelegate =
  31. @"FirebaseMessagingUseMessagingDelegateForDirectChannel";
  32. static int downstreamMessageID = 0;
  33. @interface FIRMessagingReceiver ()
  34. @property(nonatomic, strong) GULUserDefaults *defaults;
  35. @end
  36. @implementation FIRMessagingReceiver
  37. #pragma mark - Initializer
  38. - (instancetype)initWithUserDefaults:(GULUserDefaults *)defaults {
  39. self = [super init];
  40. if (self != nil) {
  41. _defaults = defaults;
  42. }
  43. return self;
  44. }
  45. #pragma mark - FIRMessagingDataMessageManager protocol
  46. - (void)didReceiveMessage:(NSDictionary *)message withIdentifier:(nullable NSString *)messageID {
  47. if (![messageID length]) {
  48. messageID = [[self class] nextMessageID];
  49. }
  50. NSInteger majorOSVersion = [[GULAppEnvironmentUtil systemVersion] integerValue];
  51. if (majorOSVersion >= 10 || self.useDirectChannel) {
  52. // iOS 10 and above or use direct channel is enabled.
  53. [self scheduleIos10NotificationForMessage:message withIdentifier:messageID];
  54. } else {
  55. // Post notification directly to AppDelegate handlers. This is valid pre-iOS 10.
  56. [self scheduleNotificationForMessage:message];
  57. }
  58. }
  59. - (void)willSendDataMessageWithID:(NSString *)messageID error:(NSError *)error {
  60. NSNotification *notification;
  61. if (error) {
  62. NSDictionary *userInfo = @{
  63. kUpstreamMessageIDUserInfoKey : [messageID copy],
  64. kUpstreamErrorUserInfoKey : error
  65. };
  66. notification = [NSNotification notificationWithName:FIRMessagingSendErrorNotification
  67. object:nil
  68. userInfo:userInfo];
  69. [[NSNotificationQueue defaultQueue] enqueueNotification:notification postingStyle:NSPostASAP];
  70. FIRMessagingLoggerDebug(kFIRMessagingMessageCodeReceiver000,
  71. @"Fail to send upstream message: %@ error: %@", messageID, error);
  72. } else {
  73. FIRMessagingLoggerDebug(kFIRMessagingMessageCodeReceiver001, @"Will send upstream message: %@",
  74. messageID);
  75. }
  76. }
  77. - (void)didSendDataMessageWithID:(NSString *)messageID {
  78. // invoke the callbacks asynchronously
  79. FIRMessagingLoggerDebug(kFIRMessagingMessageCodeReceiver002, @"Did send upstream message: %@",
  80. messageID);
  81. NSNotification * notification =
  82. [NSNotification notificationWithName:FIRMessagingSendSuccessNotification
  83. object:nil
  84. userInfo:@{ kUpstreamMessageIDUserInfoKey : [messageID copy] }];
  85. [[NSNotificationQueue defaultQueue] enqueueNotification:notification postingStyle:NSPostASAP];
  86. }
  87. - (void)didDeleteMessagesOnServer {
  88. FIRMessagingLoggerDebug(kFIRMessagingMessageCodeReceiver003,
  89. @"Will send deleted messages notification");
  90. NSNotification * notification =
  91. [NSNotification notificationWithName:FIRMessagingMessagesDeletedNotification
  92. object:nil];
  93. [[NSNotificationQueue defaultQueue] enqueueNotification:notification postingStyle:NSPostASAP];
  94. }
  95. #pragma mark - Private Helpers
  96. // As the new UserNotifications framework in iOS 10 doesn't support constructor/mutation for
  97. // UNNotification object, FCM can't inject the message to the app with UserNotifications framework.
  98. // Define our own protocol, which means app developers need to implement two interfaces to receive
  99. // display notifications and data messages respectively for devices running iOS 10 or above. Devices
  100. // running iOS 9 or below are not affected.
  101. - (void)scheduleIos10NotificationForMessage:(NSDictionary *)message
  102. withIdentifier:(NSString *)messageID {
  103. FIRMessagingRemoteMessage *wrappedMessage = [[FIRMessagingRemoteMessage alloc] init];
  104. // TODO: wrap title, body, badge and other fields
  105. wrappedMessage.appData = [message copy];
  106. wrappedMessage.messageID = messageID;
  107. [self.delegate receiver:self receivedRemoteMessage:wrappedMessage];
  108. }
  109. - (void)scheduleNotificationForMessage:(NSDictionary *)message {
  110. SEL newNotificationSelector =
  111. @selector(application:didReceiveRemoteNotification:fetchCompletionHandler:);
  112. SEL oldNotificationSelector = @selector(application:didReceiveRemoteNotification:);
  113. dispatch_async(dispatch_get_main_queue(), ^{
  114. UIApplication *application = FIRMessagingUIApplication();
  115. if (!application) {
  116. return;
  117. }
  118. id<UIApplicationDelegate> appDelegate = [application delegate];
  119. if ([appDelegate respondsToSelector:newNotificationSelector]) {
  120. // Try the new remote notification callback
  121. [appDelegate application:application
  122. didReceiveRemoteNotification:message
  123. fetchCompletionHandler:^(UIBackgroundFetchResult result) {
  124. }];
  125. } else if ([appDelegate respondsToSelector:oldNotificationSelector]) {
  126. // Try the old remote notification callback
  127. #pragma clang diagnostic push
  128. #pragma clang diagnostic ignored "-Wdeprecated-declarations"
  129. [appDelegate application:application didReceiveRemoteNotification:message];
  130. #pragma clang diagnostic pop
  131. } else {
  132. FIRMessagingLoggerError(kFIRMessagingMessageCodeReceiver005,
  133. @"None of the remote notification callbacks implemented by "
  134. @"UIApplicationDelegate");
  135. }
  136. });
  137. }
  138. + (NSString *)nextMessageID {
  139. @synchronized (self) {
  140. ++downstreamMessageID;
  141. return [NSString stringWithFormat:@"gcm-%d", downstreamMessageID];
  142. }
  143. }
  144. - (BOOL)useDirectChannel {
  145. // Check storage
  146. id shouldUseMessagingDelegate =
  147. [_defaults objectForKey:kFIRMessagingUserDefaultsKeyUseMessagingDelegate];
  148. if (shouldUseMessagingDelegate) {
  149. return [shouldUseMessagingDelegate boolValue];
  150. }
  151. // Check Info.plist
  152. shouldUseMessagingDelegate =
  153. [[NSBundle mainBundle] objectForInfoDictionaryKey:kFIRMessagingPlistUseMessagingDelegate];
  154. if (shouldUseMessagingDelegate) {
  155. return [shouldUseMessagingDelegate boolValue];
  156. }
  157. // If none of above exists, we go back to default behavior which is NO.
  158. return NO;
  159. }
  160. - (void)setUseDirectChannel:(BOOL)useDirectChannel {
  161. BOOL shouldUseMessagingDelegate = [self useDirectChannel];
  162. if (useDirectChannel != shouldUseMessagingDelegate) {
  163. [_defaults setBool:useDirectChannel forKey:kFIRMessagingUserDefaultsKeyUseMessagingDelegate];
  164. [_defaults synchronize];
  165. }
  166. }
  167. @end