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

Janic Duplessis's avatar
Janic Duplessis committed
3 4 5 6
#import <React/RCTBridge.h>
#import <React/RCTConvert.h>
#import <React/RCTEventDispatcher.h>
#import <React/RCTUtils.h>
Libin Lu's avatar
init  
Libin Lu committed
7

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

Libin Lu's avatar
init  
Libin Lu committed
11 12 13 14 15 16 17 18 19 20 21 22
#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
23 24
@implementation RCTConvert (NSCalendarUnit)

Libin Lu's avatar
Libin Lu committed
25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41
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
42
{
Libin Lu's avatar
Libin Lu committed
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 70 71 72 73 74 75 76 77 78 79 80
  NSDictionary<NSString *, id> *details = [self NSDictionary:json];
  UNMutableNotificationContent *content = [UNMutableNotificationContent new];
  content.title =[RCTConvert NSString:details[@"title"]];
  content.body =[RCTConvert NSString:details[@"body"]];
  content.sound = [RCTConvert NSString:details[@"sound"]] ?: [UNNotificationSound defaultSound];
  content.categoryIdentifier = [RCTConvert NSString:details[@"click_action"]];
  content.userInfo = details;
  content.badge = [RCTConvert NSNumber:details[@"badge"]];
  
  NSDate *fireDate = [RCTConvert NSDate:details[@"fire_date"]] ?: [NSDate date];
  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
81
  }
Libin Lu's avatar
Libin Lu committed
82 83 84
  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
85 86 87 88 89 90 91 92 93 94 95
}

@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
96 97 98
  if([notification respondsToSelector:@selector(setAlertTitle:)]){
    [notification setAlertTitle:[RCTConvert NSString:details[@"title"]]];
  }
Libin Lu's avatar
Libin Lu committed
99 100 101 102 103 104 105 106 107 108
  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
109

110
@implementation RNFIRMessaging
Libin Lu's avatar
init  
Libin Lu committed
111 112 113 114 115 116 117 118 119 120 121 122 123

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
124
  
Libin Lu's avatar
init  
Libin Lu committed
125
  [[NSNotificationCenter defaultCenter] addObserver:self
Libin Lu's avatar
Libin Lu committed
126
                                           selector:@selector(handleNotificationReceived:)
Libin Lu's avatar
init  
Libin Lu committed
127 128 129 130 131 132 133 134 135 136 137
                                               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
138
  
Libin Lu's avatar
init  
Libin Lu committed
139 140 141
  [[NSNotificationCenter defaultCenter]
   addObserver:self selector:@selector(onTokenRefresh)
   name:kFIRInstanceIDTokenRefreshNotification object:nil];
Libin Lu's avatar
Libin Lu committed
142
  
143
  [[NSNotificationCenter defaultCenter]
Libin Lu's avatar
Libin Lu committed
144 145 146
   addObserver:self selector:@selector(sendDataMessageFailure:)
   name:FIRMessagingSendErrorNotification object:nil];
  
147
  [[NSNotificationCenter defaultCenter]
Libin Lu's avatar
Libin Lu committed
148 149
   addObserver:self selector:@selector(sendDataMessageSuccess:)
   name:FIRMessagingSendSuccessNotification object:nil];
Libin Lu's avatar
Libin Lu committed
150
  
Libin Lu's avatar
Libin Lu committed
151 152
  // For iOS 10 data message (sent via FCM)
  [[FIRMessaging messaging] setRemoteMessageDelegate:self];
Libin Lu's avatar
init  
Libin Lu committed
153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171
}

- (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
172
RCT_EXPORT_METHOD(getInitialNotification:(RCTPromiseResolveBlock)resolve rejecter:(RCTPromiseRejectBlock)reject){
Libin Lu's avatar
Libin Lu committed
173 174 175 176 177
  NSDictionary *localUserInfo = _bridge.launchOptions[UIApplicationLaunchOptionsLocalNotificationKey];
  if(localUserInfo){
    resolve([localUserInfo copy]);
    return;
  }
Libin Lu's avatar
Libin Lu committed
178 179 180 181
  resolve([_bridge.launchOptions[UIApplicationLaunchOptionsRemoteNotificationKey] copy]);
}

RCT_EXPORT_METHOD(getFCMToken:(RCTPromiseResolveBlock)resolve rejecter:(RCTPromiseRejectBlock)reject)
Libin Lu's avatar
init  
Libin Lu committed
182 183 184 185 186 187
{
  resolve([[FIRInstanceID instanceID] token]);
}

- (void) onTokenRefresh
{
188
  [_bridge.eventDispatcher sendDeviceEventWithName:@"FCMTokenRefreshed" body:[[FIRInstanceID instanceID] token]];
Libin Lu's avatar
init  
Libin Lu committed
189 190 191 192
}

RCT_EXPORT_METHOD(requestPermissions)
{
Libin Lu's avatar
Libin Lu committed
193 194 195
  if (RCTRunningInAppExtension()) {
    return;
  }
Libin Lu's avatar
Libin Lu committed
196 197 198 199 200 201 202 203 204 205 206 207 208
  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
209
  } else {
Libin Lu's avatar
Libin Lu committed
210 211 212 213 214 215 216 217 218 219 220 221
    // 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) {
     }
     ];
#endif
Libin Lu's avatar
Libin Lu committed
222
  }
Libin Lu's avatar
Libin Lu committed
223 224 225 226
  
  [[UIApplication sharedApplication] registerForRemoteNotifications];
}

227 228 229 230 231 232 233 234 235 236
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
237 238 239 240 241 242
// Receive data message on iOS 10 devices.
- (void)applicationReceivedRemoteMessage:(FIRMessagingRemoteMessage *)remoteMessage {
  [_bridge.eventDispatcher sendDeviceEventWithName:FCMNotificationReceived body:[remoteMessage appData]];
}

RCT_EXPORT_METHOD(presentLocalNotification:(UNNotificationRequest *)data resolver:(RCTPromiseResolveBlock)resolve rejecter:(RCTPromiseRejectBlock)reject)
Libin Lu's avatar
Libin Lu committed
243
{
Libin Lu's avatar
Libin Lu committed
244 245 246 247 248 249 250 251 252 253 254 255 256 257
  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
258 259
}

Libin Lu's avatar
Libin Lu committed
260
RCT_EXPORT_METHOD(scheduleLocalNotification:(id)data resolver:(RCTPromiseResolveBlock)resolve rejecter:(RCTPromiseRejectBlock)reject)
Libin Lu's avatar
Libin Lu committed
261
{
Libin Lu's avatar
Libin Lu committed
262 263 264 265 266 267 268 269 270 271 272 273 274 275
  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
276 277 278 279
}

RCT_EXPORT_METHOD(cancelAllLocalNotifications)
{
Libin Lu's avatar
Libin Lu committed
280 281 282 283 284 285
  if([UNUserNotificationCenter currentNotificationCenter] != nil){
    [[UNUserNotificationCenter currentNotificationCenter] removeAllPendingNotificationRequests];
    [[UNUserNotificationCenter currentNotificationCenter] removeAllDeliveredNotifications];
  } else {
    [RCTSharedApplication() cancelAllLocalNotifications];
  }
Libin Lu's avatar
Libin Lu committed
286 287 288 289
}

RCT_EXPORT_METHOD(cancelLocalNotification:(NSString*) notificationId)
{
Libin Lu's avatar
Libin Lu committed
290 291 292 293 294 295 296 297
  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
298 299 300 301
    }
  }
}

Libin Lu's avatar
Libin Lu committed
302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322
RCT_EXPORT_METHOD(getScheduledLocalNotifications:(RCTPromiseResolveBlock)resolve rejecter:(RCTPromiseRejectBlock)reject)
{
  if([UNUserNotificationCenter currentNotificationCenter] != nil){
    [[UNUserNotificationCenter currentNotificationCenter] getPendingNotificationRequestsWithCompletionHandler:^(NSArray<UNNotificationRequest *> * _Nonnull requests) {
      NSMutableArray* list = [[NSMutableArray alloc] init];
      for(UNNotificationRequest * notif in requests){
        NSString* interval;
        UNMutableNotificationContent *content = notif.content;
        [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
323 324 325 326 327 328 329 330 331 332
RCT_EXPORT_METHOD(setBadgeNumber: (NSInteger*) number)
{
  [RCTSharedApplication() setApplicationIconBadgeNumber:number];
}

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

333 334 335 336 337 338 339
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
340
  
341
  NSDictionary *imMessage = [NSDictionary dictionaryWithDictionary:upstreamMessage];
Libin Lu's avatar
Libin Lu committed
342
  
343 344
  int64_t ttl = 3600;
  NSString * receiver = [NSString stringWithFormat:@"%@@gcm.googleapis.com", senderId];
Libin Lu's avatar
Libin Lu committed
345
  
346 347
  NSUUID *uuid = [NSUUID UUID];
  NSString * messageID = [uuid UUIDString];
Libin Lu's avatar
Libin Lu committed
348
  
349 350 351
  [[FIRMessaging messaging]sendMessage:imMessage to:receiver withMessageID:messageID timeToLive:ttl];
}

Libin Lu's avatar
Libin Lu committed
352
- (void)handleNotificationReceived:(NSNotification *)notification
Libin Lu's avatar
init  
Libin Lu committed
353
{
Libin Lu's avatar
Libin Lu committed
354 355 356 357 358 359 360 361
  if([notification.userInfo valueForKey:@"opened_from_tray"] == nil){
    NSMutableDictionary *data = [[NSMutableDictionary alloc]initWithDictionary: notification.userInfo];
    [data setValue:@(RCTSharedApplication().applicationState == UIApplicationStateInactive) forKey:@"opened_from_tray"];
    [_bridge.eventDispatcher sendDeviceEventWithName:FCMNotificationReceived body:data];
  }else{
    [_bridge.eventDispatcher sendDeviceEventWithName:FCMNotificationReceived body:notification.userInfo];
  }
  
Libin Lu's avatar
init  
Libin Lu committed
362 363
}

Libin Lu's avatar
Libin Lu committed
364
- (void)sendDataMessageFailure:(NSNotification *)notification
365
{
Libin Lu's avatar
Libin Lu committed
366 367 368
  NSString *messageID = (NSString *)notification.userInfo[@"messageID"];
  
  NSLog(@"sendDataMessageFailure: %@", messageID);
369 370
}

Libin Lu's avatar
Libin Lu committed
371
- (void)sendDataMessageSuccess:(NSNotification *)notification
372
{
Libin Lu's avatar
Libin Lu committed
373 374 375
  NSString *messageID = (NSString *)notification.userInfo[@"messageID"];
  
  NSLog(@"sendDataMessageSuccess: %@", messageID);
376 377
}

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