1// Copyright 2021-present 650 Industries. All rights reserved.
2
3#import <EXNotifications/EXBackgroundNotificationTasksModule.h>
4#import <EXNotifications/EXBackgroundRemoteNotificationConsumer.h>
5#import <ExpoModulesCore/EXTaskInterface.h>
6
7@implementation EXBackgroundRemoteNotificationConsumer
8
9+ (BOOL)supportsLaunchReason:(EXTaskLaunchReason)launchReason
10{
11  return launchReason == EXTaskLaunchReasonRemoteNotification;
12}
13
14- (NSString *)taskType
15{
16  return @"remote-notification";
17}
18
19// Associating task to the consumer.
20- (void)didRegisterTask:(id<EXTaskInterface>)task
21{
22  _task = task;
23}
24
25// Method that is being called when the JS app just finished launching,
26// after the native app was launched with the launch reason supported by the consumer.
27// For background notifications, `application:didReceiveRemoteNotification:fetchCompletionHandler:` is the entry point of this method,
28// so the task can be executed immediately here if the app is not foregrounded.
29- (void)didBecomeReadyToExecuteWithData:(NSDictionary *)data
30{
31  if ([[UIApplication sharedApplication] applicationState] != UIApplicationStateActive) {
32    [_task executeWithData:data withError:nil];
33  }
34}
35
36// Translate result received from JS to another (native) type that is then used for example as an argument in completion callbacks.
37- (NSUInteger)normalizeTaskResult:(id)result
38{
39  if (!result || result == [NSNull null]) {
40    return UIBackgroundFetchResultNoData;
41  }
42  switch ([result unsignedIntegerValue]) {
43    case EXBackgroundNotificationResultNewData:
44      return UIBackgroundFetchResultNewData;
45    case EXBackgroundNotificationResultFailed:
46      return UIBackgroundFetchResultFailed;
47    case EXBackgroundNotificationResultNoData:
48    default:
49      return UIBackgroundFetchResultNoData;
50  }
51}
52
53@end
54