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

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

18 19 20 21
const DEVICE_NOTIFICATION_ACTION_RECEIVED = "notificationActionReceived";

const _exportedEvents = [
  DEVICE_REMOTE_NOTIFICATIONS_REGISTERED_EVENT,
22
  DEVICE_REMOTE_NOTIFICATIONS_REGISTRATION_FAILED_EVENT,
23 24 25 26 27
  DEVICE_PUSH_KIT_REGISTERED_EVENT,
  DEVICE_NOTIFICATION_RECEIVED_FOREGROUND_EVENT,
  DEVICE_NOTIFICATION_RECEIVED_BACKGROUND_EVENT,
  DEVICE_NOTIFICATION_OPENED_EVENT
];
Leon Mok's avatar
Leon Mok committed
28 29
const _notificationHandlers = new Map();
const _actionHandlers = new Map();
30
let _actionListener;
Lidan Hifi's avatar
Lidan Hifi committed
31

32
export class NotificationAction {
mlanter's avatar
mlanter committed
33 34 35
  options: Object;
  handler: Function;

36 37 38 39 40 41 42
  constructor(options: Object, handler: Function) {
    this.options = options;
    this.handler = handler;
  }
}

export class NotificationCategory {
mlanter's avatar
mlanter committed
43 44
  options: Object;

45 46 47 48 49
  constructor(options: Object) {
    this.options = options;
  }
}

50
export default class NotificationsIOS {
Lidan Hifi's avatar
Lidan Hifi committed
51 52 53 54 55 56
  /**
   * Attaches a listener to remote notification events while the app is running
   * in the foreground or the background.
   *
   * Valid events are:
   *
57
   * - `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
58 59 60 61 62
   * - `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) {
63 64 65 66
    if (_exportedEvents.indexOf(type) !== -1) {
      let listener;

      if (type === DEVICE_REMOTE_NOTIFICATIONS_REGISTERED_EVENT) {
67
        listener = DeviceEventEmitter.addListener(
68 69 70
          DEVICE_REMOTE_NOTIFICATIONS_REGISTERED_EVENT,
          registration => handler(registration.deviceToken)
        );
71
      } else if (type === DEVICE_REMOTE_NOTIFICATIONS_REGISTRATION_FAILED_EVENT) {
72
        listener = DeviceEventEmitter.addListener(
73 74 75
          DEVICE_REMOTE_NOTIFICATIONS_REGISTRATION_FAILED_EVENT,
          error => handler(error)
        );
76
      } else if (type === DEVICE_PUSH_KIT_REGISTERED_EVENT) {
77
        listener = DeviceEventEmitter.addListener(
78 79 80 81
          DEVICE_PUSH_KIT_REGISTERED_EVENT,
          registration => handler(registration.pushKitToken)
        );
      } else {
82
        listener = DeviceEventEmitter.addListener(
83 84 85 86
          type,
          notification => handler(new IOSNotification(notification))
        );
      }
Lidan Hifi's avatar
Lidan Hifi committed
87

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

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

    }
  }
106

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

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

113
      actionHandler(action, () => {
114
        NativeRNNotifications.completionHandler(action.completionKey);
115
      });
116
    }
117 118 119 120 121
  }

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

    if (categories) {
126
      // subscribe once for all actions
127
      _actionListener = NativeAppEventEmitter.addListener(DEVICE_NOTIFICATION_ACTION_RECEIVED, this._actionHandlerDispatcher.bind(this));
128

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

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

141
    NativeRNNotifications.requestPermissionsWithCategories(notificationCategories);
142 143 144 145 146 147
  }

  /**
   * Unregister for all remote notifications received via Apple Push Notification service.
   */
  static abandonPermissions() {
148
    NativeRNNotifications.abandonPermissions();
149
  }
150 151 152 153 154 155 156 157 158 159 160 161

  /**
   * Removes the event listener. Do this in `componentWillUnmount` to prevent
   * memory leaks
   */
  static resetCategories() {
    if (_actionListener) {
      _actionListener.remove();
    }

    _actionHandlers.clear();
  }
162

163
  static getBadgesCount(callback: Function) {
164
    NativeRNNotifications.getBadgesCount(callback);
165 166
  }

167
  static setBadgesCount(count: number) {
168
    NativeRNNotifications.setBadgesCount(count);
169 170
  }

171
  static registerPushKit() {
172
    NativeRNNotifications.registerPushKit();
173 174 175
  }

  static backgroundTimeRemaining(callback: Function) {
176
    NativeRNNotifications.backgroundTimeRemaining(callback);
177 178
  }

179
  static consumeBackgroundQueue() {
180
    NativeRNNotifications.consumeBackgroundQueue();
181 182
  }

183
  static log(message: string) {
184
    NativeRNNotifications.log(message);
185
  }
186

187
  static async getInitialNotification() {
188
    const notification = await NativeRNNotifications.getInitialNotification();
189 190 191 192 193 194 195
    if (notification) {
      return new IOSNotification(notification);
    } else {
      return undefined;
    }
  }

196 197 198 199 200 201 202 203 204
  /**
   * Presenting local notification
   *
   * notification is an object containing:
   *
   * - `alertBody` : The message displayed in the notification alert.
   * - `alertTitle` : The message title displayed in the notification.
   * - `alertAction` : The "action" displayed beneath an actionable notification. Defaults to "view";
   * - `soundName` : The sound played when the notification is fired (optional).
205
   * - `silent`    : If true, the notification sound will be suppressed (optional).
206 207 208 209 210
   * - `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
211
    const notificationId = uuid.v4();
212
    NativeRNNotifications.localNotification(notification, notificationId);
213 214 215 216 217

    return notificationId;
  }

  static cancelLocalNotification(notificationId: String) {
218
    NativeRNNotifications.cancelLocalNotification(notificationId);
219 220 221
  }

  static cancelAllLocalNotifications() {
222
    NativeRNNotifications.cancelAllLocalNotifications();
223
  }
224

Ran Greenberg's avatar
Ran Greenberg committed
225
  static isRegisteredForRemoteNotifications() {
226
    return NativeRNNotifications.isRegisteredForRemoteNotifications();
227
  }
Ryan Eberhardt's avatar
Ryan Eberhardt committed
228 229

  static checkPermissions() {
230
    return NativeRNNotifications.checkPermissions();
Ryan Eberhardt's avatar
Ryan Eberhardt committed
231
  }
232

233 234 235 236
  /**
   * Remove all delivered notifications from Notification Center
   */
  static removeAllDeliveredNotifications() {
237
    return NativeRNNotifications.removeAllDeliveredNotifications();
238 239 240 241 242 243 244
  }

  /**
   * Removes the specified notifications from Notification Center
   *
   * @param identifiers Array of notification identifiers
   */
245
  static removeDeliveredNotifications(identifiers: Array<String>) {
246
    return NativeRNNotifications.removeDeliveredNotifications(identifiers);
247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263
  }

  /**
   * 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.
   * - `alertBody` : The message displayed in the notification alert.
   * - `alertTitle` : The message title displayed in the notification.
   * - `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.
   */
264
  static getDeliveredNotifications(callback: (notifications: Array<Object>) => void) {
265
    return NativeRNNotifications.getDeliveredNotifications(callback);
266
  }
Lidan Hifi's avatar
Lidan Hifi committed
267
}