notifications-events.md 2.54 KB
Newer Older
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
---
id: notifications-events
title: Handling Notification Events
sidebar_label: Events
---

## <img src="https://upload.wikimedia.org/wikipedia/commons/thumb/f/fa/Apple_logo_black.svg/2000px-Apple_logo_black.svg.png" width=30/> iOS

When a push notification is received by the device, the application can be in one of the following states:

1. **Forground:** When the app is running and is used by the user right now; in this case, a `notificationReceived` event will be fired, do not forget to invoke `completion()` callback.

Finally, when a notification is _opened_ by the device user (i.e. tapped-on), a `notificationOpened` event is fired, here as well you need to remember invoking `completion()` callback.

Example:

```javascript
constructor() {
    Notifications.events().registerNotificationReceived((notification: Notification, completion: (response: NotificationCompletion) => void) => {
			console.log("Notification Received - Foreground", notification.data);

			// Calling completion on iOS with `alert: true` will present the native iOS inApp notification.
			completion({alert: true, sound: true, badge: false});
		});

    Notifications.events().registerRemoteNotificationOpened((notification: Notification, completion: () => void, action: NotificationActionResponse) => {
			console.log("Notification opened by device user", notification.data);
			console.log(`Notification opened with an action identifier: ${action.identifier} and response text: ${action.text}`);
			completion();
		});
}
```

### Notification Object

When you receive a push notification, you'll get an instance of [Notification](notification-object) object, contains the following methods:

## Querying initial notification

React-Native's [`PushNotificationsIOS.getInitialNotification()`](https://facebook.github.io/react-native/docs/pushnotificationios.html#getinitialnotification) allows for the async retrieval of the original notification used to open the App on iOS, but it has no equivalent implementation for Android.

```javascript
import {Notifications} from 'react-native-notifications';

Notifications.getInitialNotification()
  .then((notification) => {
  		console.log("Initial notification was:", (notification ? notification.data : 'N/A'));
	})  	
  .catch((err) => console.error("getInitialNotifiation() failed", err));

```

> **Note**
> 
> Notifications are considered 'initial' under the following terms:

> - User tapped on a notification, _AND_ -
> - App was either not running at all ("dead" state), _OR_ it existed in the background with **no running activities** associated with it.