RNFIRMessaging.m 20.3 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 7
@import UserNotifications;

Libin Lu's avatar
init  
Libin Lu committed
8 9 10 11 12 13 14 15 16 17 18
#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
19 20
NSString *const FCMTokenRefreshed = @"FCMTokenRefreshed";
NSString *const FCMDirectChannelConnectionChanged = @"FCMDirectChannelConnectionChanged";
Libin Lu's avatar
init  
Libin Lu committed
21

Libin Lu's avatar
Libin Lu committed
22 23
@implementation RCTConvert (NSCalendarUnit)

Libin Lu's avatar
Libin Lu committed
24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40
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
41
{
Libin Lu's avatar
Libin Lu committed
42 43 44 45 46 47 48 49 50
    NSDictionary<NSString *, id> *details = [self NSDictionary:json];
    UNMutableNotificationContent *content = [UNMutableNotificationContent new];
    content.title =[RCTConvert NSString:details[@"title"]];
    content.body =[RCTConvert NSString:details[@"body"]];
    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
    }
Libin Lu's avatar
Libin Lu committed
52 53 54 55 56 57 58 59
    content.categoryIdentifier = [RCTConvert NSString:details[@"click_action"]];
    content.userInfo = details;
    content.badge = [RCTConvert NSNumber:details[@"badge"]];

    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
60
    }
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 89

    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
90
    }
Libin Lu's avatar
Libin Lu committed
91 92 93
    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
94 95 96 97 98 99 100 101
}

@end

@implementation RCTConvert (UILocalNotification)

+ (UILocalNotification *)UILocalNotification:(id)json
{
Libin Lu's avatar
Libin Lu committed
102 103 104 105 106 107 108 109 110 111 112 113 114 115
    NSDictionary<NSString *, id> *details = [self NSDictionary:json];
    UILocalNotification *notification = [UILocalNotification new];
    notification.fireDate = [RCTConvert NSDate:details[@"fire_date"]] ?: [NSDate date];
    if([notification respondsToSelector:@selector(setAlertTitle:)]){
        [notification setAlertTitle:[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;
Libin Lu's avatar
Libin Lu committed
116
}
Libin Lu's avatar
Libin Lu committed
117 118 119 120 121 122 123 124

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

RCT_ENUM_CONVERTER(UNNotificationPresentationOptions, (@{
Libin Lu's avatar
Libin Lu committed
125 126
                                                         @"UNNotificationPresentationOptionAll": @(UNNotificationPresentationOptionAlert | UNNotificationPresentationOptionBadge | UNNotificationPresentationOptionSound),
                                                         @"UNNotificationPresentationOptionNone": @(UNNotificationPresentationOptionNone)}), UIBackgroundFetchResultNoData, integerValue)
Libin Lu's avatar
Libin Lu committed
127 128 129 130

@end

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

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

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
- (NSArray<NSString *> *)supportedEvents {
Libin Lu's avatar
Libin Lu committed
139
    return @[FCMNotificationReceived, FCMTokenRefreshed, FCMDirectChannelConnectionChanged];
Libin Lu's avatar
Libin Lu committed
140 141
}

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

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

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

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

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

Libin Lu's avatar
Libin Lu committed
178
- (instancetype)init {
Libin Lu's avatar
Libin Lu committed
179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201
    self = [super init];
    [[NSNotificationCenter defaultCenter] addObserver:self
                                             selector:@selector(handleNotificationReceived:)
                                                 name:FCMNotificationReceived
                                               object:nil];

    [[NSNotificationCenter defaultCenter]
     addObserver:self selector:@selector(sendDataMessageFailure:)
     name:FIRMessagingSendErrorNotification object:nil];

    [[NSNotificationCenter defaultCenter]
     addObserver:self selector:@selector(sendDataMessageSuccess:)
     name:FIRMessagingSendSuccessNotification object:nil];

    [[NSNotificationCenter defaultCenter]
     addObserver:self selector:@selector(connectionStateChanged:)
     name:FIRMessagingConnectionStateChangedNotification object:nil];

    // For iOS 10 data message (sent via FCM)
    dispatch_async(dispatch_get_main_queue(), ^{
        [[FIRMessaging messaging] setDelegate:self];
    });
    return self;
Libin Lu's avatar
init  
Libin Lu committed
202 203
}

Libin Lu's avatar
Libin Lu committed
204
RCT_EXPORT_METHOD(enableDirectChannel)
Libin Lu's avatar
init  
Libin Lu committed
205
{
Libin Lu's avatar
Libin Lu committed
206
    [[FIRMessaging messaging] setShouldEstablishDirectChannel:@YES];
Libin Lu's avatar
init  
Libin Lu committed
207 208
}

Libin Lu's avatar
Libin Lu committed
209
RCT_EXPORT_METHOD(isDirectChannelEstablished:(RCTPromiseResolveBlock)resolve rejecter:(RCTPromiseRejectBlock)reject)
Libin Lu's avatar
init  
Libin Lu committed
210
{
Libin Lu's avatar
Libin Lu committed
211
    resolve([[FIRMessaging messaging] isDirectChannelEstablished] ? @YES: @NO);
Libin Lu's avatar
init  
Libin Lu committed
212 213
}

Libin Lu's avatar
Libin Lu committed
214
RCT_EXPORT_METHOD(getInitialNotification:(RCTPromiseResolveBlock)resolve rejecter:(RCTPromiseRejectBlock)reject)
Libin Lu's avatar
Libin Lu committed
215
{
Libin Lu's avatar
Libin Lu committed
216 217 218 219 220 221
    UILocalNotification *localUserInfo = self.bridge.launchOptions[UIApplicationLaunchOptionsLocalNotificationKey];
    if (localUserInfo) {
        resolve([[localUserInfo userInfo] copy]);
    } else {
        resolve([self.bridge.launchOptions[UIApplicationLaunchOptionsRemoteNotificationKey] copy]);
    }
Libin Lu's avatar
Libin Lu committed
222 223
}

Libin Lu's avatar
Libin Lu committed
224
RCT_EXPORT_METHOD(getAPNSToken:(RCTPromiseResolveBlock)resolve rejecter:(RCTPromiseRejectBlock)reject)
Libin Lu's avatar
init  
Libin Lu committed
225
{
Libin Lu's avatar
Libin Lu committed
226
    resolve([FIRMessaging messaging].APNSToken);
Libin Lu's avatar
init  
Libin Lu committed
227 228
}

Libin Lu's avatar
Libin Lu committed
229
RCT_EXPORT_METHOD(getFCMToken:(RCTPromiseResolveBlock)resolve rejecter:(RCTPromiseRejectBlock)reject)
Libin Lu's avatar
init  
Libin Lu committed
230
{
Libin Lu's avatar
Libin Lu committed
231
    resolve([FIRMessaging messaging].FCMToken);
Libin Lu's avatar
Libin Lu committed
232 233 234
}

- (void)messaging:(nonnull FIRMessaging *)messaging didRefreshRegistrationToken:(nonnull NSString *)fcmToken {
Libin Lu's avatar
Libin Lu committed
235
    [self sendEventWithName:FCMTokenRefreshed body:fcmToken];
Libin Lu's avatar
init  
Libin Lu committed
236 237
}

Libin Lu's avatar
Libin Lu committed
238
RCT_EXPORT_METHOD(requestPermissions:(RCTPromiseResolveBlock)resolve rejecter:(RCTPromiseRejectBlock)reject)
Libin Lu's avatar
init  
Libin Lu committed
239
{
Libin Lu's avatar
Libin Lu committed
240 241
    if (RCTRunningInAppExtension()) {
        return;
Libin Lu's avatar
Libin Lu committed
242
    }
Libin Lu's avatar
Libin Lu committed
243 244 245 246 247 248 249 250 251 252 253 254
    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 10 or later
Libin Lu's avatar
Libin Lu committed
255
#if defined(__IPHONE_10_0) && __IPHONE_OS_VERSION_MAX_ALLOWED >= __IPHONE_10_0
Libin Lu's avatar
Libin Lu committed
256 257 258 259 260 261 262 263 264 265 266 267 268 269
        UNAuthorizationOptions authOptions =
        UNAuthorizationOptionAlert
        | UNAuthorizationOptionSound
        | UNAuthorizationOptionBadge;
        [[UNUserNotificationCenter currentNotificationCenter]
         requestAuthorizationWithOptions:authOptions
         completionHandler:^(BOOL granted, NSError * _Nullable error) {
             if(granted){
                 resolve(nil);
             } else{
                 reject(@"notification_error", @"Failed to grand permission", error);
             }
         }
         ];
Libin Lu's avatar
Libin Lu committed
270
#endif
Libin Lu's avatar
Libin Lu committed
271 272 273
    }

    [[UIApplication sharedApplication] registerForRemoteNotifications];
Libin Lu's avatar
Libin Lu committed
274 275
}

276 277
RCT_EXPORT_METHOD(subscribeToTopic: (NSString*) topic)
{
Libin Lu's avatar
Libin Lu committed
278
    [[FIRMessaging messaging] subscribeToTopic:topic];
279 280 281 282
}

RCT_EXPORT_METHOD(unsubscribeFromTopic: (NSString*) topic)
{
Libin Lu's avatar
Libin Lu committed
283
    [[FIRMessaging messaging] unsubscribeFromTopic:topic];
284 285
}

Libin Lu's avatar
Libin Lu committed
286 287
// Receive data message on iOS 10 devices.
- (void)applicationReceivedRemoteMessage:(FIRMessagingRemoteMessage *)remoteMessage {
Libin Lu's avatar
Libin Lu committed
288
    [self sendEventWithName:FCMNotificationReceived body:[remoteMessage appData]];
Libin Lu's avatar
Libin Lu committed
289 290
}

Libin Lu's avatar
Libin Lu committed
291
RCT_EXPORT_METHOD(presentLocalNotification:(id)data resolver:(RCTPromiseResolveBlock)resolve rejecter:(RCTPromiseRejectBlock)reject)
Libin Lu's avatar
Libin Lu committed
292
{
Libin Lu's avatar
Libin Lu committed
293 294 295 296 297 298 299 300 301 302 303 304
    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];
Libin Lu's avatar
Libin Lu committed
305
        resolve(nil);
Libin Lu's avatar
Libin Lu committed
306
    }
Libin Lu's avatar
Libin Lu committed
307 308
}

Libin Lu's avatar
Libin Lu committed
309
RCT_EXPORT_METHOD(scheduleLocalNotification:(id)data resolver:(RCTPromiseResolveBlock)resolve rejecter:(RCTPromiseRejectBlock)reject)
Libin Lu's avatar
Libin Lu committed
310
{
Libin Lu's avatar
Libin Lu committed
311 312 313 314 315 316 317 318 319 320 321 322
    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];
Libin Lu's avatar
Libin Lu committed
323
        resolve(nil);
Libin Lu's avatar
Libin Lu committed
324
    }
Libin Lu's avatar
Libin Lu committed
325 326
}

Libin Lu's avatar
Libin Lu committed
327
RCT_EXPORT_METHOD(removeDeliveredNotification:(NSString*) notificationId)
Libin Lu's avatar
Libin Lu committed
328
{
Libin Lu's avatar
Libin Lu committed
329 330 331
    if([UNUserNotificationCenter currentNotificationCenter] != nil){
        [[UNUserNotificationCenter currentNotificationCenter] removeDeliveredNotificationsWithIdentifiers:@[notificationId]];
    }
Libin Lu's avatar
Libin Lu committed
332 333 334 335
}

RCT_EXPORT_METHOD(removeAllDeliveredNotifications)
{
Libin Lu's avatar
Libin Lu committed
336 337 338 339 340
    if([UNUserNotificationCenter currentNotificationCenter] != nil){
        [[UNUserNotificationCenter currentNotificationCenter] removeAllDeliveredNotifications];
    } else {
        [RCTSharedApplication() setApplicationIconBadgeNumber: 0];
    }
Libin Lu's avatar
Libin Lu committed
341 342
}

Libin Lu's avatar
Libin Lu committed
343 344
RCT_EXPORT_METHOD(cancelAllLocalNotifications)
{
Libin Lu's avatar
Libin Lu committed
345 346 347 348 349
    if([UNUserNotificationCenter currentNotificationCenter] != nil){
        [[UNUserNotificationCenter currentNotificationCenter] removeAllPendingNotificationRequests];
    } else {
        [RCTSharedApplication() cancelAllLocalNotifications];
    }
Libin Lu's avatar
Libin Lu committed
350 351 352 353
}

RCT_EXPORT_METHOD(cancelLocalNotification:(NSString*) notificationId)
{
Libin Lu's avatar
Libin Lu committed
354 355 356 357 358 359 360 361 362
    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
363 364 365
    }
}

Libin Lu's avatar
Libin Lu committed
366
RCT_EXPORT_METHOD(getScheduledLocalNotifications:(RCTPromiseResolveBlock)resolve rejecter:(RCTPromiseRejectBlock)reject)
Libin Lu's avatar
Libin Lu committed
367
{
Libin Lu's avatar
Libin Lu committed
368 369 370 371 372 373 374 375 376 377 378 379 380 381 382
    if([UNUserNotificationCenter currentNotificationCenter] != nil){
        [[UNUserNotificationCenter currentNotificationCenter] getPendingNotificationRequestsWithCompletionHandler:^(NSArray<UNNotificationRequest *> * _Nonnull requests) {
            NSMutableArray* list = [[NSMutableArray alloc] init];
            for(UNNotificationRequest * notif in requests){
                UNNotificationContent *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
383 384 385
    }
}

Libin Lu's avatar
Libin Lu committed
386
RCT_EXPORT_METHOD(setBadgeNumber: (NSInteger) number)
Libin Lu's avatar
Libin Lu committed
387
{
Libin Lu's avatar
Libin Lu committed
388
    [RCTSharedApplication() setApplicationIconBadgeNumber:number];
Libin Lu's avatar
Libin Lu committed
389 390
}

Libin Lu's avatar
Libin Lu committed
391
RCT_EXPORT_METHOD(getBadgeNumber: (RCTPromiseResolveBlock)resolve rejecter:(RCTPromiseRejectBlock)reject)
Libin Lu's avatar
Libin Lu committed
392
{
Libin Lu's avatar
Libin Lu committed
393
    resolve(@([RCTSharedApplication() applicationIconBadgeNumber]));
Libin Lu's avatar
Libin Lu committed
394 395
}

396 397
RCT_EXPORT_METHOD(send:(NSString*)senderId withPayload:(NSDictionary *)message)
{
Libin Lu's avatar
Libin Lu committed
398 399 400 401 402 403 404 405 406 407 408 409 410 411 412
    NSMutableDictionary * mMessage = [message mutableCopy];
    NSMutableDictionary * upstreamMessage = [[NSMutableDictionary alloc] init];
    for (NSString* key in mMessage) {
        upstreamMessage[key] = [NSString stringWithFormat:@"%@", [mMessage valueForKey:key]];
    }

    NSDictionary *imMessage = [NSDictionary dictionaryWithDictionary:upstreamMessage];

    int64_t ttl = 3600;
    NSString * receiver = [NSString stringWithFormat:@"%@@gcm.googleapis.com", senderId];

    NSUUID *uuid = [NSUUID UUID];
    NSString * messageID = [uuid UUIDString];

    [[FIRMessaging messaging]sendMessage:imMessage to:receiver withMessageID:messageID timeToLive:ttl];
413 414
}

Libin Lu's avatar
Libin Lu committed
415
RCT_EXPORT_METHOD(finishRemoteNotification: (NSString *)completionHandlerId fetchResult:(UIBackgroundFetchResult)result){
Libin Lu's avatar
Libin Lu committed
416 417 418 419 420 421 422
    RCTRemoteNotificationCallback completionHandler = self.notificationCallbacks[completionHandlerId];
    if (!completionHandler) {
        RCTLogError(@"There is no completion handler with completionHandlerId: %@", completionHandlerId);
        return;
    }
    completionHandler(result);
    [self.notificationCallbacks removeObjectForKey:completionHandlerId];
Libin Lu's avatar
Libin Lu committed
423 424 425
}

RCT_EXPORT_METHOD(finishWillPresentNotification: (NSString *)completionHandlerId fetchResult:(UNNotificationPresentationOptions)result){
Libin Lu's avatar
Libin Lu committed
426 427 428 429 430 431 432
    RCTWillPresentNotificationCallback completionHandler = self.notificationCallbacks[completionHandlerId];
    if (!completionHandler) {
        RCTLogError(@"There is no completion handler with completionHandlerId: %@", completionHandlerId);
        return;
    }
    completionHandler(result);
    [self.notificationCallbacks removeObjectForKey:completionHandlerId];
Libin Lu's avatar
Libin Lu committed
433 434 435
}

RCT_EXPORT_METHOD(finishNotificationResponse: (NSString *)completionHandlerId){
Libin Lu's avatar
Libin Lu committed
436 437 438 439 440 441 442
    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
443 444
}

Libin Lu's avatar
Libin Lu committed
445
- (void)handleNotificationReceived:(NSNotification *)notification
Libin Lu's avatar
init  
Libin Lu committed
446
{
Libin Lu's avatar
Libin Lu committed
447 448 449 450 451 452 453 454 455 456
    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
457
    }
Libin Lu's avatar
Libin Lu committed
458 459 460

    [self sendEventWithName:FCMNotificationReceived body:data];

Libin Lu's avatar
init  
Libin Lu committed
461 462
}

Libin Lu's avatar
Libin Lu committed
463
- (void)sendDataMessageFailure:(NSNotification *)notification
464
{
Libin Lu's avatar
Libin Lu committed
465 466 467
    NSString *messageID = (NSString *)notification.userInfo[@"messageID"];

    NSLog(@"sendDataMessageFailure: %@", messageID);
468 469
}

Libin Lu's avatar
Libin Lu committed
470
- (void)sendDataMessageSuccess:(NSNotification *)notification
471
{
Libin Lu's avatar
Libin Lu committed
472 473 474
    NSString *messageID = (NSString *)notification.userInfo[@"messageID"];

    NSLog(@"sendDataMessageSuccess: %@", messageID);
475 476
}

Libin Lu's avatar
Libin Lu committed
477 478
- (void)connectionStateChanged:(NSNotification *)notification
{
Libin Lu's avatar
Libin Lu committed
479 480
    [self sendEventWithName:FCMDirectChannelConnectionChanged body:[FIRMessaging messaging].isDirectChannelEstablished ? @YES: @NO];
    NSLog(@"connectionStateChanged: %@", [FIRMessaging messaging].isDirectChannelEstablished ? @"connected": @"disconnected");
Libin Lu's avatar
Libin Lu committed
481 482
}

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