FIRMessagingReceiver.m 7.4 KB

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