RNFIRMesssaging.m 10.8 KB
Newer Older
1
#import "RNFIRMessaging.h"
Libin Lu's avatar
init  
Libin Lu committed
2 3 4 5 6 7

#import "RCTBridge.h"
#import "RCTConvert.h"
#import "RCTEventDispatcher.h"
#import "RCTUtils.h"

Libin Lu's avatar
Libin Lu committed
8 9
@import UserNotifications;

Libin Lu's avatar
init  
Libin Lu committed
10 11 12 13 14 15 16 17 18 19 20
#if __IPHONE_OS_VERSION_MIN_REQUIRED < __IPHONE_8_0

#define UIUserNotificationTypeAlert UIRemoteNotificationTypeAlert
#define UIUserNotificationTypeBadge UIRemoteNotificationTypeBadge
#define UIUserNotificationTypeSound UIRemoteNotificationTypeSound
#define UIUserNotificationTypeNone  UIRemoteNotificationTypeNone
#define UIUserNotificationType      UIRemoteNotificationType

#endif

NSString *const FCMNotificationReceived = @"FCMNotificationReceived";
Libin Lu's avatar
Libin Lu committed
21
NSString *const FCMLocalNotificationReceived = @"FCMLocalNotificationReceived";
Libin Lu's avatar
init  
Libin Lu committed
22

Libin Lu's avatar
Libin Lu committed
23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69
@implementation RCTConvert (NSCalendarUnit)

+ (NSCalendarUnit *)NSCalendarUnit:(id)json
{
  NSString* key = [self NSString:json];
  if([key isEqualToString:@"minute"]){
    return NSCalendarUnitMinute;
  }
  if([key isEqualToString:@"second"]){
    return NSCalendarUnitSecond;
  }
  if([key isEqualToString:@"day"]){
    return NSCalendarUnitDay;
  }
  if([key isEqualToString:@"month"]){
    return NSCalendarUnitMonth;
  }
  if([key isEqualToString:@"week"]){
    return NSCalendarUnitWeekOfYear;
  }
  if([key isEqualToString:@"year"]){
    return NSCalendarUnitYear;
  }
  return 0;
}

@end

@implementation RCTConvert (UILocalNotification)

+ (UILocalNotification *)UILocalNotification:(id)json
{
  NSDictionary<NSString *, id> *details = [self NSDictionary:json];
  UILocalNotification *notification = [UILocalNotification new];
  notification.fireDate = [RCTConvert NSDate:details[@"fire_date"]] ?: [NSDate date];
  notification.alertTitle = [RCTConvert NSString:details[@"title"]];
  notification.alertBody = [RCTConvert NSString:details[@"body"]];
  notification.alertAction = [RCTConvert NSString:details[@"alert_action"]];
  notification.soundName = [RCTConvert NSString:details[@"sound"]] ?: UILocalNotificationDefaultSoundName;
  notification.userInfo = details;
  notification.category = [RCTConvert NSString:details[@"click_action"]];
  notification.repeatInterval = [RCTConvert NSCalendarUnit:details[@"repeat_interval"]];
  notification.applicationIconBadgeNumber = [RCTConvert NSInteger:details[@"badge"]];
  return notification;
}

@end
Libin Lu's avatar
init  
Libin Lu committed
70

71
@implementation RNFIRMessaging
Libin Lu's avatar
init  
Libin Lu committed
72 73 74 75 76 77 78 79 80 81 82 83 84

RCT_EXPORT_MODULE()

@synthesize bridge = _bridge;

- (void)dealloc
{
  [[NSNotificationCenter defaultCenter] removeObserver:self];
}

- (void)setBridge:(RCTBridge *)bridge
{
  _bridge = bridge;
Libin Lu's avatar
Libin Lu committed
85
  
Libin Lu's avatar
init  
Libin Lu committed
86 87 88 89 90 91 92 93 94 95 96 97 98
  [[NSNotificationCenter defaultCenter] addObserver:self
                                           selector:@selector(handleRemoteNotificationReceived:)
                                               name:FCMNotificationReceived
                                             object:nil];
  
  [[NSNotificationCenter defaultCenter] addObserver:self
                                           selector:@selector(disconnectFCM)
                                               name:UIApplicationDidEnterBackgroundNotification
                                             object:nil];
  [[NSNotificationCenter defaultCenter] addObserver:self
                                           selector:@selector(connectToFCM)
                                               name:UIApplicationDidBecomeActiveNotification
                                             object:nil];
Libin Lu's avatar
Libin Lu committed
99 100 101 102 103
  
  [[NSNotificationCenter defaultCenter] addObserver:self
                                           selector:@selector(handleFCMLocalNotificationReceived:)
                                               name:FCMLocalNotificationReceived
                                             object:nil];
Libin Lu's avatar
init  
Libin Lu committed
104 105 106
  [[NSNotificationCenter defaultCenter]
   addObserver:self selector:@selector(onTokenRefresh)
   name:kFIRInstanceIDTokenRefreshNotification object:nil];
Libin Lu's avatar
Libin Lu committed
107
  
Libin Lu's avatar
init  
Libin Lu committed
108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126
}

- (void)connectToFCM
{
  [[FIRMessaging messaging] connectWithCompletion:^(NSError * _Nullable error) {
    if (error != nil) {
      NSLog(@"Unable to connect to FCM. %@", error);
    } else {
      NSLog(@"Connected to FCM.");
    }
  }];
}

- (void)disconnectFCM
{
  [[FIRMessaging messaging] disconnect];
  NSLog(@"Disconnected from FCM");
}

Libin Lu's avatar
Libin Lu committed
127 128 129 130 131
RCT_EXPORT_METHOD(getInitialNotification:(RCTPromiseResolveBlock)resolve rejecter:(RCTPromiseRejectBlock)reject){
  resolve([_bridge.launchOptions[UIApplicationLaunchOptionsRemoteNotificationKey] copy]);
}

RCT_EXPORT_METHOD(getFCMToken:(RCTPromiseResolveBlock)resolve rejecter:(RCTPromiseRejectBlock)reject)
Libin Lu's avatar
init  
Libin Lu committed
132 133 134 135
{
  resolve([[FIRInstanceID instanceID] token]);
}

Libin Lu's avatar
Libin Lu committed
136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181
RCT_EXPORT_METHOD(getScheduledLocalNotifications:(RCTPromiseResolveBlock)resolve rejecter:(RCTPromiseRejectBlock)reject)
{
  NSMutableArray* list = [[NSMutableArray alloc] init];
  for(UILocalNotification * notif in [RCTSharedApplication() scheduledLocalNotifications]){
    NSString* interval;
    
    switch(notif.repeatInterval){
      case NSCalendarUnitMinute:
        interval = @"minute";
        break;
      case NSCalendarUnitSecond:
        interval = @"second";
        break;
      case NSCalendarUnitDay:
        interval = @"day";
        break;
      case NSCalendarUnitMonth:
        interval = @"month";
        break;
      case NSCalendarUnitWeekOfYear:
        interval = @"week";
        break;
      case NSCalendarUnitYear:
        interval = @"year";
        break;
    }
    NSMutableDictionary *formattedLocalNotification = [NSMutableDictionary dictionary];
    if (notif.fireDate) {
      NSDateFormatter *formatter = [NSDateFormatter new];
      [formatter setDateFormat:@"yyyy-MM-dd'T'HH:mm:ss.SSSZZZZZ"];
      NSString *fireDateString = [formatter stringFromDate:notif.fireDate];
      formattedLocalNotification[@"fire_date"] = fireDateString;
    }
    formattedLocalNotification[@"alert_action"] = RCTNullIfNil(notif.alertAction);
    formattedLocalNotification[@"body"] = RCTNullIfNil(notif.alertBody);
    formattedLocalNotification[@"title"] = RCTNullIfNil(notif.alertTitle);
    formattedLocalNotification[@"badge"] = @(notif.applicationIconBadgeNumber);
    formattedLocalNotification[@"click_action"] = RCTNullIfNil(notif.category);
    formattedLocalNotification[@"sound"] = RCTNullIfNil(notif.soundName);
    formattedLocalNotification[@"repeat_interval"] = RCTNullIfNil(interval);
    formattedLocalNotification[@"data"] = RCTNullIfNil(RCTJSONClean(notif.userInfo));
    [list addObject:formattedLocalNotification];
  }
  resolve(list);
}

Libin Lu's avatar
init  
Libin Lu committed
182 183
- (void) onTokenRefresh
{
184
  [_bridge.eventDispatcher sendDeviceEventWithName:@"FCMTokenRefreshed" body:[[FIRInstanceID instanceID] token]];
Libin Lu's avatar
init  
Libin Lu committed
185 186 187 188
}

RCT_EXPORT_METHOD(requestPermissions)
{
Libin Lu's avatar
Libin Lu committed
189 190 191
  if (RCTRunningInAppExtension()) {
    return;
  }
Libin Lu's avatar
Libin Lu committed
192 193 194 195 196 197 198 199 200 201 202 203 204
  if (floor(NSFoundationVersionNumber) <= NSFoundationVersionNumber_iOS_9_x_Max) {
    UIUserNotificationType allNotificationTypes =
    (UIUserNotificationTypeSound | UIUserNotificationTypeAlert | UIUserNotificationTypeBadge);
    UIApplication *app = RCTSharedApplication();
    if ([app respondsToSelector:@selector(registerUserNotificationSettings:)]) {
      //iOS 8 or later
      UIUserNotificationSettings *notificationSettings =
      [UIUserNotificationSettings settingsForTypes:(NSUInteger)allNotificationTypes categories:nil];
      [app registerUserNotificationSettings:notificationSettings];
    } else {
      //iOS 7 or below
      [app registerForRemoteNotificationTypes:(NSUInteger)allNotificationTypes];
    }
Libin Lu's avatar
Libin Lu committed
205
  } else {
Libin Lu's avatar
Libin Lu committed
206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222
    // iOS 10 or later
#if defined(__IPHONE_10_0) && __IPHONE_OS_VERSION_MAX_ALLOWED >= __IPHONE_10_0
    UNAuthorizationOptions authOptions =
    UNAuthorizationOptionAlert
    | UNAuthorizationOptionSound
    | UNAuthorizationOptionBadge;
    [[UNUserNotificationCenter currentNotificationCenter]
     requestAuthorizationWithOptions:authOptions
     completionHandler:^(BOOL granted, NSError * _Nullable error) {
     }
     ];
    
    // For iOS 10 display notification (sent via APNS)
    [[UNUserNotificationCenter currentNotificationCenter] setDelegate:self];
    // For iOS 10 data message (sent via FCM)
    [[FIRMessaging messaging] setRemoteMessageDelegate:self];
#endif
Libin Lu's avatar
Libin Lu committed
223
  }
Libin Lu's avatar
Libin Lu committed
224 225 226 227 228 229 230 231 232 233 234
  
  [[UIApplication sharedApplication] registerForRemoteNotifications];
}

#if defined(__IPHONE_10_0) && __IPHONE_OS_VERSION_MAX_ALLOWED >= __IPHONE_10_0
// Receive displayed notifications for iOS 10 devices.
- (void)userNotificationCenter:(UNUserNotificationCenter *)center
       willPresentNotification:(UNNotification *)notification
         withCompletionHandler:(void (^)(UNNotificationPresentationOptions))completionHandler {
  NSDictionary *userInfo = notification.request.content.userInfo;
  [_bridge.eventDispatcher sendDeviceEventWithName:FCMNotificationReceived body:userInfo];
Libin Lu's avatar
init  
Libin Lu committed
235 236
}

Libin Lu's avatar
Libin Lu committed
237 238 239 240 241 242
// Receive data message on iOS 10 devices.
- (void)applicationReceivedRemoteMessage:(FIRMessagingRemoteMessage *)remoteMessage {
  [_bridge.eventDispatcher sendDeviceEventWithName:FCMNotificationReceived body:[remoteMessage appData]];
}
#endif

243 244 245 246 247 248 249 250 251 252
RCT_EXPORT_METHOD(subscribeToTopic: (NSString*) topic)
{
  [[FIRMessaging messaging] subscribeToTopic:topic];
}

RCT_EXPORT_METHOD(unsubscribeFromTopic: (NSString*) topic)
{
  [[FIRMessaging messaging] unsubscribeFromTopic:topic];
}

Libin Lu's avatar
Libin Lu committed
253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294
RCT_EXPORT_METHOD(presentLocalNotification:(UILocalNotification *)notification)
{
  [RCTSharedApplication() presentLocalNotificationNow:notification];
}

RCT_EXPORT_METHOD(scheduleLocalNotification:(UILocalNotification *)notification)
{
  [RCTSharedApplication() scheduleLocalNotification:notification];
}

RCT_EXPORT_METHOD(cancelAllLocalNotifications)
{
  [RCTSharedApplication() cancelAllLocalNotifications];
}

RCT_EXPORT_METHOD(cancelLocalNotification:(NSString*) notificationId)
{
  for (UILocalNotification *notification in [UIApplication sharedApplication].scheduledLocalNotifications) {
    NSDictionary<NSString *, id> *notificationInfo = notification.userInfo;
    if([notificationId isEqualToString:[notificationInfo valueForKey:@"id"]]){
      [[UIApplication sharedApplication] cancelLocalNotification:notification];
    }
  }
}

RCT_EXPORT_METHOD(setBadgeNumber: (NSInteger*) number)
{
  [RCTSharedApplication() setApplicationIconBadgeNumber:number];
}

RCT_EXPORT_METHOD(getBadgeNumber: (RCTPromiseResolveBlock)resolve rejecter:(RCTPromiseRejectBlock)reject)
{
  resolve(@([RCTSharedApplication() applicationIconBadgeNumber]));
}

- (void)handleFCMLocalNotificationReceived:(UILocalNotification *)notification
{
  NSMutableDictionary *data = [[NSMutableDictionary alloc]initWithDictionary: notification.userInfo];
  [data setValue:@(RCTSharedApplication().applicationState == UIApplicationStateInactive) forKey:@"opened_from_tray"];
  [_bridge.eventDispatcher sendDeviceEventWithName:FCMLocalNotificationReceived body:data];
}

Libin Lu's avatar
init  
Libin Lu committed
295 296
- (void)handleRemoteNotificationReceived:(NSNotification *)notification
{
Libin Lu's avatar
Libin Lu committed
297 298
  NSMutableDictionary *data = [[NSMutableDictionary alloc]initWithDictionary: notification.userInfo];
  [data setValue:@(RCTSharedApplication().applicationState == UIApplicationStateInactive) forKey:@"opened_from_tray"];
Libin Lu's avatar
Libin Lu committed
299
  [_bridge.eventDispatcher sendDeviceEventWithName:FCMNotificationReceived body:data];
Libin Lu's avatar
init  
Libin Lu committed
300 301 302
}

@end