index.ios.js 2.06 KB
Newer Older
Lidan Hifi's avatar
Lidan Hifi committed
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61
/**
 * @providesModule SmartNotifications
 * @flow
 */
'use strict';
import { NativeModules, DeviceEventEmitter } from 'react-native';
import Map from 'core-js/library/es6/map';
var NativeSmartNotifications = NativeModules.SmartNotifications;

var DEVICE_NOTIFICATION_RECEIVED_FOREGROUND_EVENT = 'notificationReceivedForeground';
var DEVICE_NOTIFICATION_RECEIVED_BACKGROUND_EVENT = 'notificationReceivedBackground';
var DEVICE_NOTIFICATION_OPENED_EVENT = 'notificationOpened';

var _notificationHandlers = new Map();

class SmartNotificationsIOS {
  /**
   * Attaches a listener to remote notification events while the app is running
   * in the foreground or the background.
   *
   * Valid events are:
   *
   * - `notificationReceivedForeground` : Fired when a notification (local / remote) is received when app is on foreground state.
   * - `notificationReceivedBackground`: Fired when a background notification is received.
   * - `notificationOpened`: Fired when a notification (local / remote) is opened.
   */
  static addEventListener(type: string, handler: Function) {
    if (type === DEVICE_NOTIFICATION_RECEIVED_FOREGROUND_EVENT ||
        type === DEVICE_NOTIFICATION_RECEIVED_BACKGROUND_EVENT ||
        type === DEVICE_NOTIFICATION_OPENED_EVENT) {
          var listener = DeviceEventEmitter.addListener(
            type,
            (notification) => {
              handler(notification);
            }
          );

          _notificationHandlers.set(handler, listener);
    }
  }

  /**
   * Removes the event listener. Do this in `componentWillUnmount` to prevent
   * memory leaks
   */
  static removeEventListener(type: string, handler: Function) {
    if (type === DEVICE_NOTIFICATION_RECEIVED_FOREGROUND_EVENT ||
        type === DEVICE_NOTIFICATION_RECEIVED_BACKGROUND_EVENT ||
        type === DEVICE_NOTIFICATION_OPENED_EVENT) {
          var listener = _notificationHandlers.get(handler);
          if (!listener) {
            return;
          }

          listener.remove();
          _notificationHandlers.delete(handler);
    }
  }
}

module.exports = SmartNotificationsIOS;