RNFIRMessaging.m 19.2 KB
Newer Older
1
#import "RNFIRMessaging.h"
Libin Lu's avatar
init  
Libin Lu committed
2

Libin Lu's avatar
Libin Lu committed
3 4
#import <React/RCTConvert.h>
#import <React/RCTUtils.h>
Libin Lu's avatar
init  
Libin Lu committed
5

Libin Lu's avatar
Libin Lu committed
6
@import UserNotifications;
7
#import <FirebaseInstanceID/FirebaseInstanceID.h>
Libin Lu's avatar
Libin Lu committed
8

Libin Lu's avatar
init  
Libin Lu committed
9 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 22
@implementation RCTConvert (NSCalendarUnit)

Libin Lu's avatar
Libin Lu committed
23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39
RCT_ENUM_CONVERTER(NSCalendarUnit,
                   (@{
                      @"year": @(NSCalendarUnitYear),
                      @"month": @(NSCalendarUnitMonth),
                      @"week": @(NSCalendarUnitWeekOfYear),
                      @"day": @(NSCalendarUnitDay),
                      @"hour": @(NSCalendarUnitHour),
                      @"minute": @(NSCalendarUnitMinute)
                      }),
                   0,
                   integerValue)
@end


@implementation RCTConvert (UNNotificationRequest)

+ (UNNotificationRequest *)UNNotificationRequest:(id)json
Libin Lu's avatar
Libin Lu committed
40
{
Libin Lu's avatar
Libin Lu committed
41 42 43 44
  NSDictionary<NSString *, id> *details = [self NSDictionary:json];
  UNMutableNotificationContent *content = [UNMutableNotificationContent new];
  content.title =[RCTConvert NSString:details[@"title"]];
  content.body =[RCTConvert NSString:details[@"body"]];
Libin Lu's avatar
Libin Lu committed
45 46 47 48 49 50
  NSString* sound = [RCTConvert NSString:details[@"sound"]];
  if(sound != nil){
    content.sound = [UNNotificationSound soundNamed:sound];
  }else{
    content.sound = [UNNotificationSound defaultSound];
  }
Libin Lu's avatar
Libin Lu committed
51 52 53 54
  content.categoryIdentifier = [RCTConvert NSString:details[@"click_action"]];
  content.userInfo = details;
  content.badge = [RCTConvert NSNumber:details[@"badge"]];
  
Libin Lu's avatar
Libin Lu committed
55 56 57 58 59 60
  NSDate *fireDate = [RCTConvert NSDate:details[@"fire_date"]];
  
  if(fireDate == nil){
    return [UNNotificationRequest requestWithIdentifier:[RCTConvert NSString:details[@"id"]] content:content trigger:nil];
  }
  
Libin Lu's avatar
Libin Lu committed
61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88
  NSCalendarUnit interval = [RCTConvert NSCalendarUnit:details[@"repeat_interval"]];
  NSCalendarUnit unitFlags;
  switch (interval) {
    case NSCalendarUnitMinute: {
      unitFlags = NSCalendarUnitSecond;
      break;
    }
    case NSCalendarUnitHour: {
      unitFlags = NSCalendarUnitMinute | NSCalendarUnitSecond;
      break;
    }
    case NSCalendarUnitDay: {
      unitFlags = NSCalendarUnitHour | NSCalendarUnitMinute | NSCalendarUnitSecond;
      break;
    }
    case NSCalendarUnitWeekOfYear: {
      unitFlags = NSCalendarUnitWeekday | NSCalendarUnitHour | NSCalendarUnitMinute | NSCalendarUnitSecond;
      break;
    }
    case NSCalendarUnitMonth:{
      unitFlags = NSCalendarUnitDay | NSCalendarUnitHour | NSCalendarUnitMinute | NSCalendarUnitSecond;
    }
    case NSCalendarUnitYear:{
      unitFlags = NSCalendarUnitMonth | NSCalendarUnitDay | NSCalendarUnitHour | NSCalendarUnitMinute | NSCalendarUnitSecond;
    }
    default:
      unitFlags = NSCalendarUnitDay | NSCalendarUnitMonth | NSCalendarUnitYear | NSCalendarUnitHour | NSCalendarUnitMinute | NSCalendarUnitSecond;
      break;
Libin Lu's avatar
Libin Lu committed
89
  }
Libin Lu's avatar
Libin Lu committed
90 91 92
  NSDateComponents *components = [[NSCalendar currentCalendar] components:unitFlags fromDate:fireDate];
  UNCalendarNotificationTrigger *trigger = [UNCalendarNotificationTrigger triggerWithDateMatchingComponents:components repeats:interval != 0];
  return [UNNotificationRequest requestWithIdentifier:[RCTConvert NSString:details[@"id"]] content:content trigger:trigger];
Libin Lu's avatar
Libin Lu committed
93 94 95 96 97 98 99 100 101 102 103
}

@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];
Libin Lu's avatar
Libin Lu committed
104 105 106
  if([notification respondsToSelector:@selector(setAlertTitle:)]){
    [notification setAlertTitle:[RCTConvert NSString:details[@"title"]]];
  }
Libin Lu's avatar
Libin Lu committed
107 108 109 110 111 112 113 114 115
  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;
}
Libin Lu's avatar
Libin Lu committed
116 117 118 119 120 121 122 123 124 125 126 127 128 129 130

RCT_ENUM_CONVERTER(UIBackgroundFetchResult, (@{
                                               @"UIBackgroundFetchResultNewData": @(UIBackgroundFetchResultNewData),
                                               @"UIBackgroundFetchResultNoData": @(UIBackgroundFetchResultNoData),
                                               @"UIBackgroundFetchResultFailed": @(UIBackgroundFetchResultFailed),
                                               }), UIBackgroundFetchResultNoData, integerValue)

RCT_ENUM_CONVERTER(UNNotificationPresentationOptions, (@{
                                               @"UNNotificationPresentationOptionAll": @(UNNotificationPresentationOptionAlert | UNNotificationPresentationOptionBadge | UNNotificationPresentationOptionSound),
                                               @"UNNotificationPresentationOptionNone": @(UNNotificationPresentationOptionNone)}), UIBackgroundFetchResultNoData, integerValue)

@end

@interface RNFIRMessaging ()
  @property (nonatomic, strong) NSMutableDictionary *notificationCallbacks;
Libin Lu's avatar
Libin Lu committed
131
@end
Libin Lu's avatar
init  
Libin Lu committed
132

133
@implementation RNFIRMessaging
Libin Lu's avatar
init  
Libin Lu committed
134 135

@synthesize bridge = _bridge;
Libin Lu's avatar
Libin Lu committed
136
RCT_EXPORT_MODULE();
Libin Lu's avatar
init  
Libin Lu committed
137

Libin Lu's avatar
Libin Lu committed
138
+ (void)didReceiveRemoteNotification:(nonnull NSDictionary *)userInfo fetchCompletionHandler:(nonnull RCTRemoteNotificationCallback)completionHandler {
Libin Lu's avatar
Libin Lu committed
139
  NSMutableDictionary* data = [[NSMutableDictionary alloc] initWithDictionary: userInfo];
Libin Lu's avatar
Libin Lu committed
140
  [data setValue:@"remote_notification" forKey:@"_notificationType"];
Libin Lu's avatar
Libin Lu committed
141 142 143 144 145 146
  [data setValue:@(RCTSharedApplication().applicationState == UIApplicationStateInactive) forKey:@"opened_from_tray"];
  [[NSNotificationCenter defaultCenter] postNotificationName:FCMNotificationReceived object:self userInfo:@{@"data": data, @"completionHandler": completionHandler}];
}

+ (void)didReceiveLocalNotification:(UILocalNotification *)notification {
  NSMutableDictionary* data = [[NSMutableDictionary alloc] initWithDictionary: notification.userInfo];
Libin Lu's avatar
Libin Lu committed
147
  [data setValue:@"local_notification" forKey:@"_notificationType"];
Libin Lu's avatar
Libin Lu committed
148
  [[NSNotificationCenter defaultCenter] postNotificationName:FCMNotificationReceived object:self userInfo:@{@"data": data}];
Libin Lu's avatar
Libin Lu committed
149 150
}

Libin Lu's avatar
Libin Lu committed
151
+ (void)didReceiveNotificationResponse:(UNNotificationResponse *)response withCompletionHandler:(nonnull RCTNotificationResponseCallback)completionHandler
Libin Lu's avatar
Libin Lu committed
152 153
{
  NSMutableDictionary* data = [[NSMutableDictionary alloc] initWithDictionary: response.notification.request.content.userInfo];
Libin Lu's avatar
Libin Lu committed
154
  [data setValue:@"notification_response" forKey:@"_notificationType"];
Libin Lu's avatar
Libin Lu committed
155
  [data setValue:@YES forKey:@"opened_from_tray"];
156 157 158
  if (response.actionIdentifier) {
      [data setValue:response.actionIdentifier forKey:@"_actionIdentifier"];
  }
Libin Lu's avatar
Libin Lu committed
159 160 161
  [[NSNotificationCenter defaultCenter] postNotificationName:FCMNotificationReceived object:self userInfo:@{@"data": data, @"completionHandler": completionHandler}];
}

Libin Lu's avatar
Libin Lu committed
162
+ (void)willPresentNotification:(UNNotification *)notification withCompletionHandler:(nonnull RCTWillPresentNotificationCallback)completionHandler
Libin Lu's avatar
Libin Lu committed
163 164
{
  NSMutableDictionary* data = [[NSMutableDictionary alloc] initWithDictionary: notification.request.content.userInfo];
Libin Lu's avatar
Libin Lu committed
165
  [data setValue:@"will_present_notification" forKey:@"_notificationType"];
Libin Lu's avatar
Libin Lu committed
166 167 168
  [[NSNotificationCenter defaultCenter] postNotificationName:FCMNotificationReceived object:self userInfo:@{@"data": data, @"completionHandler": completionHandler}];
}

Libin Lu's avatar
init  
Libin Lu committed
169 170 171 172 173 174 175 176
- (void)dealloc
{
  [[NSNotificationCenter defaultCenter] removeObserver:self];
}

- (void)setBridge:(RCTBridge *)bridge
{
  _bridge = bridge;
Libin Lu's avatar
Libin Lu committed
177
  
Libin Lu's avatar
init  
Libin Lu committed
178
  [[NSNotificationCenter defaultCenter] addObserver:self
Libin Lu's avatar
Libin Lu committed
179
                                           selector:@selector(handleNotificationReceived:)
Libin Lu's avatar
init  
Libin Lu committed
180 181 182 183 184 185 186 187 188 189 190
                                               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
191
  
Libin Lu's avatar
init  
Libin Lu committed
192 193 194
  [[NSNotificationCenter defaultCenter]
   addObserver:self selector:@selector(onTokenRefresh)
   name:kFIRInstanceIDTokenRefreshNotification object:nil];
Libin Lu's avatar
Libin Lu committed
195
  
196
  [[NSNotificationCenter defaultCenter]
Libin Lu's avatar
Libin Lu committed
197 198 199
   addObserver:self selector:@selector(sendDataMessageFailure:)
   name:FIRMessagingSendErrorNotification object:nil];
  
200
  [[NSNotificationCenter defaultCenter]
Libin Lu's avatar
Libin Lu committed
201 202
   addObserver:self selector:@selector(sendDataMessageSuccess:)
   name:FIRMessagingSendSuccessNotification object:nil];
Libin Lu's avatar
Libin Lu committed
203
  
Libin Lu's avatar
Libin Lu committed
204
  // For iOS 10 data message (sent via FCM)
205 206
  dispatch_async(dispatch_get_main_queue(), ^{
    [[FIRMessaging messaging] setRemoteMessageDelegate:self];
Libin Lu's avatar
Libin Lu committed
207
    [self connectToFCM];
208
  });
Libin Lu's avatar
init  
Libin Lu committed
209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227
}

- (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
228 229
RCT_EXPORT_METHOD(getInitialNotification:(RCTPromiseResolveBlock)resolve)
{
Libin Lu's avatar
Libin Lu committed
230 231 232
  UILocalNotification *localUserInfo = _bridge.launchOptions[UIApplicationLaunchOptionsLocalNotificationKey];
  if (localUserInfo) {
    resolve([[localUserInfo userInfo] copy]);
Libin Lu's avatar
Libin Lu committed
233 234
    return;
  }
Libin Lu's avatar
Libin Lu committed
235 236 237
  resolve([_bridge.launchOptions[UIApplicationLaunchOptionsRemoteNotificationKey] copy]);
}

Libin Lu's avatar
Libin Lu committed
238
RCT_EXPORT_METHOD(getFCMToken:(RCTPromiseResolveBlock)resolve)
Libin Lu's avatar
init  
Libin Lu committed
239 240 241 242 243 244
{
  resolve([[FIRInstanceID instanceID] token]);
}

- (void) onTokenRefresh
{
Libin Lu's avatar
Libin Lu committed
245
  [self sendEventWithName:@"FCMTokenRefreshed" body:[[FIRInstanceID instanceID] token]];
Libin Lu's avatar
init  
Libin Lu committed
246 247
}

Libin Lu's avatar
Libin Lu committed
248
RCT_EXPORT_METHOD(requestPermissions:(RCTPromiseResolveBlock)resolve rejecter:(RCTPromiseRejectBlock)reject)
Libin Lu's avatar
init  
Libin Lu committed
249
{
Libin Lu's avatar
Libin Lu committed
250 251 252
  if (RCTRunningInAppExtension()) {
    return;
  }
Libin Lu's avatar
Libin Lu committed
253 254 255 256 257 258 259 260 261 262
  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];
    }
Libin Lu's avatar
Libin Lu committed
263
  } else {
Libin Lu's avatar
Libin Lu committed
264 265 266 267 268 269 270 271 272
    // 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) {
Libin Lu's avatar
Libin Lu committed
273 274 275 276 277
       if(granted){
         resolve(nil);
       } else{
         reject(@"notification_error", @"Failed to grand permission", error);
       }
Libin Lu's avatar
Libin Lu committed
278 279 280
     }
     ];
#endif
Libin Lu's avatar
Libin Lu committed
281
  }
Libin Lu's avatar
Libin Lu committed
282 283 284 285
  
  [[UIApplication sharedApplication] registerForRemoteNotifications];
}

286 287 288 289 290 291 292 293 294 295
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
296 297
// Receive data message on iOS 10 devices.
- (void)applicationReceivedRemoteMessage:(FIRMessagingRemoteMessage *)remoteMessage {
Libin Lu's avatar
Libin Lu committed
298
  [self sendEventWithName:FCMNotificationReceived body:[remoteMessage appData]];
Libin Lu's avatar
Libin Lu committed
299 300
}

Libin Lu's avatar
Libin Lu committed
301
RCT_EXPORT_METHOD(presentLocalNotification:(id)data resolver:(RCTPromiseResolveBlock)resolve rejecter:(RCTPromiseRejectBlock)reject)
Libin Lu's avatar
Libin Lu committed
302
{
Libin Lu's avatar
Libin Lu committed
303 304 305 306 307 308 309 310 311 312 313 314 315 316
  if([UNUserNotificationCenter currentNotificationCenter] != nil){
    UNNotificationRequest* request = [RCTConvert UNNotificationRequest:data];
    [[UNUserNotificationCenter currentNotificationCenter] addNotificationRequest:request withCompletionHandler:^(NSError * _Nullable error) {
      if (!error) {
        resolve(nil);
      }else{
        reject(@"notification_error", @"Failed to present local notificaton", error);
      }
    }];
  }else{
    UILocalNotification* notif = [RCTConvert UILocalNotification:data];
    [RCTSharedApplication() presentLocalNotificationNow:notif];
    resolve(nil);
  }
Libin Lu's avatar
Libin Lu committed
317 318
}

Libin Lu's avatar
Libin Lu committed
319
RCT_EXPORT_METHOD(scheduleLocalNotification:(id)data resolver:(RCTPromiseResolveBlock)resolve rejecter:(RCTPromiseRejectBlock)reject)
Libin Lu's avatar
Libin Lu committed
320
{
Libin Lu's avatar
Libin Lu committed
321 322 323 324 325 326 327 328 329 330 331 332 333 334
  if([UNUserNotificationCenter currentNotificationCenter] != nil){
    UNNotificationRequest* request = [RCTConvert UNNotificationRequest:data];
    [[UNUserNotificationCenter currentNotificationCenter] addNotificationRequest:request withCompletionHandler:^(NSError * _Nullable error) {
      if (!error) {
        resolve(nil);
      }else{
        reject(@"notification_error", @"Failed to present local notificaton", error);
      }
    }];
  }else{
    UILocalNotification* notif = [RCTConvert UILocalNotification:data];
    [RCTSharedApplication() scheduleLocalNotification:notif];
    resolve(nil);
  }
Libin Lu's avatar
Libin Lu committed
335 336
}

Libin Lu's avatar
Libin Lu committed
337
RCT_EXPORT_METHOD(removeDeliveredNotification:(NSString*) notificationId)
Libin Lu's avatar
Libin Lu committed
338 339 340 341 342 343 344 345 346 347 348 349 350 351 352
{
  if([UNUserNotificationCenter currentNotificationCenter] != nil){
    [[UNUserNotificationCenter currentNotificationCenter] removeDeliveredNotificationsWithIdentifiers:@[notificationId]];
  }
}

RCT_EXPORT_METHOD(removeAllDeliveredNotifications)
{
  if([UNUserNotificationCenter currentNotificationCenter] != nil){
    [[UNUserNotificationCenter currentNotificationCenter] removeAllDeliveredNotifications];
  } else {
    [RCTSharedApplication() setApplicationIconBadgeNumber: 0];
  }
}

Libin Lu's avatar
Libin Lu committed
353 354
RCT_EXPORT_METHOD(cancelAllLocalNotifications)
{
Libin Lu's avatar
Libin Lu committed
355 356 357 358 359
  if([UNUserNotificationCenter currentNotificationCenter] != nil){
    [[UNUserNotificationCenter currentNotificationCenter] removeAllPendingNotificationRequests];
  } else {
    [RCTSharedApplication() cancelAllLocalNotifications];
  }
Libin Lu's avatar
Libin Lu committed
360 361 362 363
}

RCT_EXPORT_METHOD(cancelLocalNotification:(NSString*) notificationId)
{
Libin Lu's avatar
Libin Lu committed
364 365 366 367 368 369 370 371
  if([UNUserNotificationCenter currentNotificationCenter] != nil){
    [[UNUserNotificationCenter currentNotificationCenter] removePendingNotificationRequestsWithIdentifiers:@[notificationId]];
  }else {
    for (UILocalNotification *notification in [UIApplication sharedApplication].scheduledLocalNotifications) {
      NSDictionary<NSString *, id> *notificationInfo = notification.userInfo;
      if([notificationId isEqualToString:[notificationInfo valueForKey:@"id"]]){
        [[UIApplication sharedApplication] cancelLocalNotification:notification];
      }
Libin Lu's avatar
Libin Lu committed
372 373 374 375
    }
  }
}

Libin Lu's avatar
Libin Lu committed
376
RCT_EXPORT_METHOD(getScheduledLocalNotifications:(RCTPromiseResolveBlock)resolve)
Libin Lu's avatar
Libin Lu committed
377 378 379 380 381
{
  if([UNUserNotificationCenter currentNotificationCenter] != nil){
    [[UNUserNotificationCenter currentNotificationCenter] getPendingNotificationRequestsWithCompletionHandler:^(NSArray<UNNotificationRequest *> * _Nonnull requests) {
      NSMutableArray* list = [[NSMutableArray alloc] init];
      for(UNNotificationRequest * notif in requests){
Libin Lu's avatar
Libin Lu committed
382
        UNNotificationContent *content = notif.content;
Libin Lu's avatar
Libin Lu committed
383 384 385 386 387 388 389 390 391 392 393 394 395
        [list addObject:content.userInfo];
      }
      resolve(list);
    }];
  }else{
    NSMutableArray* list = [[NSMutableArray alloc] init];
    for(UILocalNotification * notif in [RCTSharedApplication() scheduledLocalNotifications]){
      [list addObject:notif.userInfo];
    }
    resolve(list);
  }
}

Libin Lu's avatar
Libin Lu committed
396 397
RCT_EXPORT_METHOD(setBadgeNumber: (NSInteger*) number)
{
Libin Lu's avatar
Libin Lu committed
398
  [RCTSharedApplication() setApplicationIconBadgeNumber:*number];
Libin Lu's avatar
Libin Lu committed
399 400
}

Libin Lu's avatar
Libin Lu committed
401
RCT_EXPORT_METHOD(getBadgeNumber: (RCTPromiseResolveBlock)resolve)
Libin Lu's avatar
Libin Lu committed
402 403 404 405
{
  resolve(@([RCTSharedApplication() applicationIconBadgeNumber]));
}

406 407 408 409 410 411 412
RCT_EXPORT_METHOD(send:(NSString*)senderId withPayload:(NSDictionary *)message)
{
  NSMutableDictionary * mMessage = [message mutableCopy];
  NSMutableDictionary * upstreamMessage = [[NSMutableDictionary alloc] init];
  for (NSString* key in mMessage) {
    upstreamMessage[key] = [NSString stringWithFormat:@"%@", [mMessage valueForKey:key]];
  }
Libin Lu's avatar
Libin Lu committed
413
  
414
  NSDictionary *imMessage = [NSDictionary dictionaryWithDictionary:upstreamMessage];
Libin Lu's avatar
Libin Lu committed
415
  
416 417
  int64_t ttl = 3600;
  NSString * receiver = [NSString stringWithFormat:@"%@@gcm.googleapis.com", senderId];
Libin Lu's avatar
Libin Lu committed
418
  
419 420
  NSUUID *uuid = [NSUUID UUID];
  NSString * messageID = [uuid UUIDString];
Libin Lu's avatar
Libin Lu committed
421
  
422 423 424
  [[FIRMessaging messaging]sendMessage:imMessage to:receiver withMessageID:messageID timeToLive:ttl];
}

Libin Lu's avatar
Libin Lu committed
425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454
RCT_EXPORT_METHOD(finishRemoteNotification: (NSString *)completionHandlerId fetchResult:(UIBackgroundFetchResult)result){
  RCTRemoteNotificationCallback completionHandler = self.notificationCallbacks[completionHandlerId];
  if (!completionHandler) {
    RCTLogError(@"There is no completion handler with completionHandlerId: %@", completionHandlerId);
    return;
  }
  completionHandler(result);
  [self.notificationCallbacks removeObjectForKey:completionHandlerId];
}

RCT_EXPORT_METHOD(finishWillPresentNotification: (NSString *)completionHandlerId fetchResult:(UNNotificationPresentationOptions)result){
  RCTWillPresentNotificationCallback completionHandler = self.notificationCallbacks[completionHandlerId];
  if (!completionHandler) {
    RCTLogError(@"There is no completion handler with completionHandlerId: %@", completionHandlerId);
    return;
  }
  completionHandler(result);
  [self.notificationCallbacks removeObjectForKey:completionHandlerId];
}

RCT_EXPORT_METHOD(finishNotificationResponse: (NSString *)completionHandlerId){
  RCTNotificationResponseCallback completionHandler = self.notificationCallbacks[completionHandlerId];
  if (!completionHandler) {
    RCTLogError(@"There is no completion handler with completionHandlerId: %@", completionHandlerId);
    return;
  }
  completionHandler();
  [self.notificationCallbacks removeObjectForKey:completionHandlerId];
}

Libin Lu's avatar
Libin Lu committed
455
- (void)handleNotificationReceived:(NSNotification *)notification
Libin Lu's avatar
init  
Libin Lu committed
456
{
Libin Lu's avatar
Libin Lu committed
457 458 459 460 461 462 463 464 465 466
  id completionHandler = notification.userInfo[@"completionHandler"];
  NSMutableDictionary* data = notification.userInfo[@"data"];
  if(completionHandler != nil){
    NSString *completionHandlerId = [[NSUUID UUID] UUIDString];
    if (!self.notificationCallbacks) {
      // Lazy initialization
      self.notificationCallbacks = [NSMutableDictionary dictionary];
    }
    self.notificationCallbacks[completionHandlerId] = completionHandler;
    data[@"_completionHandlerId"] = completionHandlerId;
Libin Lu's avatar
Libin Lu committed
467 468
  }
  
Libin Lu's avatar
Libin Lu committed
469
  [self sendEventWithName:FCMNotificationReceived body:data];
Libin Lu's avatar
Libin Lu committed
470
  
Libin Lu's avatar
init  
Libin Lu committed
471 472
}

Libin Lu's avatar
Libin Lu committed
473
- (void)sendDataMessageFailure:(NSNotification *)notification
474
{
Libin Lu's avatar
Libin Lu committed
475 476 477
  NSString *messageID = (NSString *)notification.userInfo[@"messageID"];
  
  NSLog(@"sendDataMessageFailure: %@", messageID);
478 479
}

Libin Lu's avatar
Libin Lu committed
480
- (void)sendDataMessageSuccess:(NSNotification *)notification
481
{
Libin Lu's avatar
Libin Lu committed
482 483 484
  NSString *messageID = (NSString *)notification.userInfo[@"messageID"];
  
  NSLog(@"sendDataMessageSuccess: %@", messageID);
485 486
}

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