FIRMessagingReceiver.m 7.3 KB

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