index.ios.js 8.85 KB
Newer Older
Lidan Hifi's avatar
Lidan Hifi committed
1 2 3
/**
 * @flow
 */
yogevbd's avatar
yogevbd committed
4 5 6 7
'use strict';
import { NativeModules, DeviceEventEmitter, NativeAppEventEmitter } from 'react-native';
import Map from 'core-js/library/es6/map';
import uuid from 'uuid';
yogevbd's avatar
WIP  
yogevbd committed
8
const NativeRNNotifications = NativeModules.RNBridgeModule; // eslint-disable-line no-unused-vars
yogevbd's avatar
yogevbd committed
9
import IOSNotification from './notification.ios';
Lidan Hifi's avatar
Lidan Hifi committed
10

yogevbd's avatar
yogevbd committed
11 12 13 14 15
export const DEVICE_REMOTE_NOTIFICATIONS_REGISTERED_EVENT = 'remoteNotificationsRegistered';
export const DEVICE_REMOTE_NOTIFICATIONS_REGISTRATION_FAILED_EVENT = 'remoteNotificationsRegistrationFailed';
export const DEVICE_PUSH_KIT_REGISTERED_EVENT = 'pushKitRegistered';
export const DEVICE_NOTIFICATION_RECEIVED_FOREGROUND_EVENT = 'notificationReceivedForeground';
export const DEVICE_NOTIFICATION_OPENED_EVENT = 'notificationOpened';
Lidan Hifi's avatar
Lidan Hifi committed
16

17 18
const _exportedEvents = [
  DEVICE_REMOTE_NOTIFICATIONS_REGISTERED_EVENT,
19
  DEVICE_REMOTE_NOTIFICATIONS_REGISTRATION_FAILED_EVENT,
20 21 22 23
  DEVICE_PUSH_KIT_REGISTERED_EVENT,
  DEVICE_NOTIFICATION_RECEIVED_FOREGROUND_EVENT,
  DEVICE_NOTIFICATION_OPENED_EVENT
];
Leon Mok's avatar
Leon Mok committed
24 25
const _notificationHandlers = new Map();
const _actionHandlers = new Map();
Lidan Hifi's avatar
Lidan Hifi committed
26

27
export class NotificationAction {
mlanter's avatar
mlanter committed
28 29
  options: Object;

yogevbd's avatar
WIP  
yogevbd committed
30
  constructor(options: Object) {
31 32 33 34 35
    this.options = options;
  }
}

export class NotificationCategory {
mlanter's avatar
mlanter committed
36 37
  options: Object;

38 39 40 41 42
  constructor(options: Object) {
    this.options = options;
  }
}

43
export default class NotificationsIOS {
Lidan Hifi's avatar
Lidan Hifi committed
44 45 46 47 48 49
  /**
   * Attaches a listener to remote notification events while the app is running
   * in the foreground or the background.
   *
   * Valid events are:
   *
50
   * - `remoteNotificationsRegistered` : Fired when the user registers for remote notifications. The handler will be invoked with a hex string representing the deviceToken.
Lidan Hifi's avatar
Lidan Hifi committed
51 52 53 54
   * - `notificationReceivedForeground` : Fired when a notification (local / remote) is received when app is on foreground state.
   * - `notificationOpened`: Fired when a notification (local / remote) is opened.
   */
  static addEventListener(type: string, handler: Function) {
55 56 57 58
    if (_exportedEvents.indexOf(type) !== -1) {
      let listener;

      if (type === DEVICE_REMOTE_NOTIFICATIONS_REGISTERED_EVENT) {
59
        listener = DeviceEventEmitter.addListener(
60 61 62
          DEVICE_REMOTE_NOTIFICATIONS_REGISTERED_EVENT,
          registration => handler(registration.deviceToken)
        );
63
      } else if (type === DEVICE_REMOTE_NOTIFICATIONS_REGISTRATION_FAILED_EVENT) {
64
        listener = DeviceEventEmitter.addListener(
65 66 67
          DEVICE_REMOTE_NOTIFICATIONS_REGISTRATION_FAILED_EVENT,
          error => handler(error)
        );
68
      } else if (type === DEVICE_PUSH_KIT_REGISTERED_EVENT) {
69
        listener = DeviceEventEmitter.addListener(
70 71 72
          DEVICE_PUSH_KIT_REGISTERED_EVENT,
          registration => handler(registration.pushKitToken)
        );
yogevbd's avatar
WIP  
yogevbd committed
73
      } else if (type === DEVICE_NOTIFICATION_RECEIVED_FOREGROUND_EVENT) {
74
        listener = DeviceEventEmitter.addListener(
75
          type,
yogevbd's avatar
WIP  
yogevbd committed
76 77 78
          ({payload, identifier}) => handler(new IOSNotification(payload), (presentingOptions) => {
            NativeRNNotifications.finishPresentingNotification(identifier, presentingOptions);
          })
79
        );
yogevbd's avatar
WIP  
yogevbd committed
80 81 82 83 84 85 86
      } else if (type === DEVICE_NOTIFICATION_OPENED_EVENT) {
        listener = DeviceEventEmitter.addListener(
          type,
          ({payload, identifier, action}) => handler(new IOSNotification(payload), () => {
            NativeRNNotifications.finishHandlingAction(identifier);
          }, action)
        );
87
      }
Lidan Hifi's avatar
Lidan Hifi committed
88

Lidan Hifi's avatar
Lidan Hifi committed
89
      _notificationHandlers.set(handler, listener);
Lidan Hifi's avatar
Lidan Hifi committed
90 91 92 93 94 95 96 97
    }
  }

  /**
   * Removes the event listener. Do this in `componentWillUnmount` to prevent
   * memory leaks
   */
  static removeEventListener(type: string, handler: Function) {
98
    if (_exportedEvents.indexOf(type) !== -1) {
Leon Mok's avatar
Leon Mok committed
99 100 101 102
      const listener = _notificationHandlers.get(handler);
      if (listener) {
        listener.remove();
        _notificationHandlers.delete(handler);
Lidan Hifi's avatar
Lidan Hifi committed
103
      }
Lidan Hifi's avatar
Lidan Hifi committed
104 105 106

    }
  }
107

108
  static _actionHandlerDispatcher(action: Object) {
Leon Mok's avatar
Leon Mok committed
109
    const actionHandler = _actionHandlers.get(action.identifier);
110 111

    if (actionHandler) {
112 113
      action.notification = new IOSNotification(action.notification);

114
      actionHandler(action, () => {
yogevbd's avatar
WIP  
yogevbd committed
115
        NativeRNNotifications.finishHandlingAction(action.identifier);
116
      });
117
    }
118 119 120 121 122
  }

  /**
   * Sets the notification categories
   */
123
  static requestPermissions(categories: Array<NotificationCategory>) {
124 125 126 127 128 129 130
    let notificationCategories = [];

    if (categories) {
      notificationCategories = categories.map(category => {
        return Object.assign({}, category.options, {
          actions: category.options.actions.map(action => {
            // subscribe to action event
131
            _actionHandlers.set(action.options.identifier, action.handler);
132 133 134 135 136 137 138

            return action.options;
          })
        });
      });
    }

139
    NativeRNNotifications.requestPermissionsWithCategories(notificationCategories);
140 141 142 143 144 145
  }

  /**
   * Unregister for all remote notifications received via Apple Push Notification service.
   */
  static abandonPermissions() {
146
    NativeRNNotifications.abandonPermissions();
147
  }
148 149 150 151 152 153 154 155

  /**
   * Removes the event listener. Do this in `componentWillUnmount` to prevent
   * memory leaks
   */
  static resetCategories() {
    _actionHandlers.clear();
  }
156

157
  static getBadgesCount(callback: Function) {
158
    NativeRNNotifications.getBadgesCount(callback);
159 160
  }

161
  static setBadgesCount(count: number) {
162
    NativeRNNotifications.setBadgesCount(count);
163 164
  }

165
  static registerPushKit() {
166
    NativeRNNotifications.registerPushKit();
167 168 169
  }

  static backgroundTimeRemaining(callback: Function) {
170
    NativeRNNotifications.backgroundTimeRemaining(callback);
171 172
  }

173
  static consumeBackgroundQueue() {
yogevbd's avatar
WIP  
yogevbd committed
174
    // NativeRNNotifications.consumeBackgroundQueue();
175 176
  }

177
  static log(message: string) {
178
    NativeRNNotifications.log(message);
179
  }
180

181
  static async getInitialNotification() {
182
    const notification = await NativeRNNotifications.getInitialNotification();
183 184 185 186 187 188 189
    if (notification) {
      return new IOSNotification(notification);
    } else {
      return undefined;
    }
  }

190 191 192 193 194
  /**
   * Presenting local notification
   *
   * notification is an object containing:
   *
yogevbd's avatar
WIP  
yogevbd committed
195 196
   * - `body` : The message displayed in the notification alert.
   * - `title` : The message title displayed in the notification.
yogevbd's avatar
yogevbd committed
197
   * - `alertAction` : The 'action' displayed beneath an actionable notification. Defaults to 'view';
yogevbd's avatar
WIP  
yogevbd committed
198
   * - `sound` : The sound played when the notification is fired (optional).
199
   * - `silent`    : If true, the notification sound will be suppressed (optional).
200 201 202 203 204
   * - `category`  : The category of this notification, required for actionable notifications (optional).
   * - `userInfo`  : An optional object containing additional notification data.
   * - `fireDate` : The date and time when the system should deliver the notification. if not specified, the notification will be dispatched immediately.
   */
  static localNotification(notification: Object) {
Leon Mok's avatar
Leon Mok committed
205
    const notificationId = uuid.v4();
206
    NativeRNNotifications.localNotification(notification, notificationId);
207 208 209 210 211

    return notificationId;
  }

  static cancelLocalNotification(notificationId: String) {
212
    NativeRNNotifications.cancelLocalNotification(notificationId);
213 214 215
  }

  static cancelAllLocalNotifications() {
216
    NativeRNNotifications.cancelAllLocalNotifications();
217
  }
218

Ran Greenberg's avatar
Ran Greenberg committed
219
  static isRegisteredForRemoteNotifications() {
220
    return NativeRNNotifications.isRegisteredForRemoteNotifications();
221
  }
Ryan Eberhardt's avatar
Ryan Eberhardt committed
222 223

  static checkPermissions() {
224
    return NativeRNNotifications.checkPermissions();
Ryan Eberhardt's avatar
Ryan Eberhardt committed
225
  }
226

227 228 229 230
  /**
   * Remove all delivered notifications from Notification Center
   */
  static removeAllDeliveredNotifications() {
231
    return NativeRNNotifications.removeAllDeliveredNotifications();
232 233 234 235 236 237 238
  }

  /**
   * Removes the specified notifications from Notification Center
   *
   * @param identifiers Array of notification identifiers
   */
239
  static removeDeliveredNotifications(identifiers: Array<String>) {
240
    return NativeRNNotifications.removeDeliveredNotifications(identifiers);
241 242 243 244 245 246 247 248 249 250
  }

  /**
   * Provides you with a list of the app’s notifications that are still displayed in Notification Center
   *
   * @param callback Function which receive an array of delivered notifications
   *
   *  A delivered notification is an object containing:
   *
   * - `identifier`  : The identifier of this notification.
yogevbd's avatar
WIP  
yogevbd committed
251 252
   * - `body` : The message displayed in the notification alert.
   * - `title` : The message title displayed in the notification.
253 254 255 256 257
   * - `category`  : The category of this notification, if has one.
   * - `userInfo`  : An optional object containing additional notification data.
   * - `thread-id`  : The thread identifier of this notification, if has one.
   * - `fireDate` : The date and time when the system should deliver the notification. if not specified, the notification will be dispatched immediately.
   */
258
  static getDeliveredNotifications(callback: (notifications: Array<Object>) => void) {
259
    return NativeRNNotifications.getDeliveredNotifications(callback);
260
  }
Lidan Hifi's avatar
Lidan Hifi committed
261
}