README.md 26.1 KB
Newer Older
Lidan's avatar
Lidan committed
1 2
# React Native Notifications [![Build Status](https://travis-ci.org/wix/react-native-notifications.svg)](https://travis-ci.org/wix/react-native-notifications)

Lidan Hifi's avatar
Lidan Hifi committed
3
Handle all the aspects of push notifications for your app, including remote and local notifications, interactive notifications, silent notifications, and more.
Lidan Hifi's avatar
Lidan Hifi committed
4

Amit Davidi's avatar
Amit Davidi committed
5
**All the native iOS notifications features are supported!** 
Lidan's avatar
Lidan committed
6

d4vidi's avatar
d4vidi committed
7
>For information regarding proper integration with [react-native-navigation](https://github.com/wix/react-native-navigation), follow [this wiki](https://github.com/wix/react-native-notifications/wiki/Android:-working-with-RNN).
Amit Davidi's avatar
Amit Davidi committed
8 9 10

## Supported Features
### iOS
Lidan Hifi's avatar
Lidan Hifi committed
11

Lidan Hifi's avatar
Lidan Hifi committed
12 13 14 15
- [Remote notifications](#handling-received-notifications).
- [Local notifications](#triggering-local-notifications).
- [Background notifications](#managed-notifications-ios-only).
- [Managed notifications](#managed-notifications-ios-only) (notifications that can be cleared from the server, like Facebook messenger and Whatsapp web).
Lidan Hifi's avatar
Lidan Hifi committed
16
- [PushKit API](#pushkit-api-ios-only) for VoIP and other background messages.
Lidan Hifi's avatar
Lidan Hifi committed
17
- [Interactive notifications](#interactive--actionable-notifications-ios-only) that allows you to provide additional functionality to your users outside of your application.
Lidan Hifi's avatar
Lidan Hifi committed
18 19 20

![Interactive notifications example](https://s3.amazonaws.com/nrjio/interactive.gif)

21
### Android
Amit Davidi's avatar
Amit Davidi committed
22

23 24
- Receiving notifications in any App state (foreground, background, "dead")
- Built-in notification drawer management
25
- High degree of code extensibility to allow for advanced custom layouts and any specific notifications behavior as available by [Android's API](https://developer.android.com/training/notify-user/build-notification.html)
26 27
- Android equivalent of React-Native's implementation of [`PushNotificationsIOS.getInitialNotification()`](https://facebook.github.io/react-native/docs/pushnotificationios.html#getinitialnotification).

28
_Upcoming: local notifications, background-state Rx queue (iOS equivalent)_
Lidan Hifi's avatar
Lidan Hifi committed
29 30

## Installation
Lidan Hifi's avatar
Lidan Hifi committed
31

Lidan Hifi's avatar
Lidan Hifi committed
32 33 34 35 36
```
$ npm install react-native-notifications --save
```

### iOS
Lidan Hifi's avatar
Lidan Hifi committed
37

Raymond Penners's avatar
Raymond Penners committed
38
First, [Manually link](https://facebook.github.io/react-native/docs/linking-libraries-ios.html#manual-linking) the library to your Xcode project.
Lidan Hifi's avatar
Lidan Hifi committed
39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59

Then, to enable notifications support add the following line at the top of your `AppDelegate.m`

```objective-c
#import "RNNotifications.h"
```

And the following methods to support registration and receiving notifications:

```objective-c
// Required to register for notifications
- (void)application:(UIApplication *)application didRegisterUserNotificationSettings:(UIUserNotificationSettings *)notificationSettings
{
  [RNNotifications didRegisterUserNotificationSettings:notificationSettings];
}

- (void)application:(UIApplication *)application didRegisterForRemoteNotificationsWithDeviceToken:(NSData *)deviceToken
{
  [RNNotifications didRegisterForRemoteNotificationsWithDeviceToken:deviceToken];
}

60 61 62 63
- (void)application:(UIApplication *)application didFailToRegisterForRemoteNotificationsWithError:(NSError *)error {
  [RNNotifications didFailToRegisterForRemoteNotificationsWithError:error];
}

Lidan Hifi's avatar
Lidan Hifi committed
64 65 66 67 68 69 70 71 72 73 74 75
// Required for the notification event.
- (void)application:(UIApplication *)application didReceiveRemoteNotification:(NSDictionary *)notification {
  [RNNotifications didReceiveRemoteNotification:notification];
}

// Required for the localNotification event.
- (void)application:(UIApplication *)application didReceiveLocalNotification:(UILocalNotification *)notification
{
  [RNNotifications didReceiveLocalNotification:notification];
}
```

76
### Android
Amit Davidi's avatar
Amit Davidi committed
77

78 79 80

Add a reference to the library's native code in your global `settings.gradle`:

81
```gradle
d4vidi's avatar
d4vidi committed
82 83
include ':reactnativenotifications'
project(':reactnativenotifications').projectDir = new File(rootProject.projectDir, '../node_modules/react-native-notifications/android')
84 85 86 87
```

Declare the library as a dependency in your **app-project's** `build.gradle`:

88
```gradle
89 90
dependencies {
	// ...
d4vidi's avatar
d4vidi committed
91
	
d4vidi's avatar
d4vidi committed
92
	compile project(':reactnativenotifications')
93 94 95
}
```

Marc Sommerhalder's avatar
Marc Sommerhalder committed
96 97 98 99 100 101 102 103 104
Add the library to your `MainApplication.java`:

```java
import com.wix.reactnativenotifications.RNNotificationsPackage;

...

    @Override
    protected List<ReactPackage> getPackages() {
105 106 107 108 109
        return Arrays.<ReactPackage>asList(
            new MainReactPackage(),
	        // ...
	        new RNNotificationsPackage(MainApplication.this)
        );
Marc Sommerhalder's avatar
Marc Sommerhalder committed
110 111
```

112 113 114
### Receiving push notifications

> This section is only necessary in case you wish to **receive** push notifications in your React-Native app.
Amit Davidi's avatar
Amit Davidi committed
115

116
Push notifications on Android are managed and dispatched using [Google's GCM service](https://developers.google.com/cloud-messaging/gcm) (now integrated into Firebase). The following installation steps are a TL;DR of [Google's GCM setup guide](https://developers.google.com/cloud-messaging/android/client). You can follow them to get GCM integrated quickly, but we recommend that you will in the very least have a peek at the guide's overview.
Amit Davidi's avatar
Amit Davidi committed
117

d4vidi's avatar
d4vidi committed
118
#### Step #1: Subscribe to Google's GCM
Amit Davidi's avatar
Amit Davidi committed
119

120
To set GCM in your app, you must first create a Google API-project and obtain a **Sender ID** and a **Server API Key**. If you have no existing API project yet, the easiest way to go about in creating one is using [this step-by-step installation process](https://developers.google.com/mobile/add); Use [this tutorial](https://code.tutsplus.com/tutorials/how-to-get-started-with-push-notifications-on-android--cms-25870) for insturctions.
Amit Davidi's avatar
Amit Davidi committed
121 122 123

Alternatively, follow [Google's complete guide](https://developers.google.com/cloud-messaging/android/client#create-an-api-project).

d4vidi's avatar
d4vidi committed
124
#### Step #2: Add Sender ID to Manifest File
Amit Davidi's avatar
Amit Davidi committed
125

126 127
Once obtained, bundle the Sender ID onto your main `manifest.xml` file:

128
```gradle
Amit Davidi's avatar
Amit Davidi committed
129 130 131 132 133
<manifest>
...
	<application>
	...
		// Replace '1234567890' with your sender ID.
134
		// IMPORTANT: Leave the trailing \0 intact!!!
Amit Davidi's avatar
Amit Davidi committed
135 136 137 138 139 140
	    <meta-data android:name="com.wix.reactnativenotifications.gcmSenderId" android:value="1234567890\0"/>
	</application>
</manifest>

```

Lidan Hifi's avatar
Lidan Hifi committed
141 142 143 144

---

## Register to Push Notifications
Lidan Hifi's avatar
Lidan Hifi committed
145

Amit Davidi's avatar
Amit Davidi committed
146 147
### iOS

Lidan Hifi's avatar
Lidan Hifi committed
148 149 150 151 152 153 154 155 156 157
In order to handle notifications, you must register before- handle `remoteNotificationsRegistered` event.

In your React Native app:

```javascript
import NotificationsIOS from 'react-native-notifications';

class App extends Component {
	constructor() {
		NotificationsIOS.addEventListener('remoteNotificationsRegistered', this.onPushRegistered.bind(this));
sportnak's avatar
sportnak committed
158
		NotificationsIOS.addEventListener('remoteNotificationsRegistrationFailed', this.onPushRegistrationFailed.bind(this));
Lidan Hifi's avatar
Lidan Hifi committed
159 160 161 162
		NotificationsIOS.requestPermissions();
	}
	
	onPushRegistered(deviceToken) {
163
		console.log("Device Token Received", deviceToken);
Lidan Hifi's avatar
Lidan Hifi committed
164
	}
165 166 167 168 169 170 171 172 173 174 175

	onPushRegistrationFailed(error) {
		// For example:
		//
		// error={
		//   domain: 'NSCocoaErroDomain',
		//   code: 3010,
		//   localizedDescription: 'remote notifications are not supported in the simulator'
		// }
		console.error(error);
	}
Lidan Hifi's avatar
Lidan Hifi committed
176 177 178 179
	
	componentWillUnmount() {
  		// prevent memory leaks!
  		NotificationsIOS.removeEventListener('remoteNotificationsRegistered', this.onPushRegistered.bind(this));
180
		NotificationsIOS.removeEventListener('remoteNotificationsRegistrationFailed', this.onPushRegistrationFailed.bind(this));
Lidan Hifi's avatar
Lidan Hifi committed
181 182 183 184 185 186 187
	}
}

```

When you have the device token, POST it to your server and register the device in your notifications provider (Amazon SNS, Azure, etc.).

Ryan Eberhardt's avatar
Ryan Eberhardt committed
188 189 190 191 192 193 194 195 196 197
You can check if the user granted permissions by calling `checkPermissions()`:

```javascript
NotificationsIOS.checkPermissions().then((currentPermissions) => {
    console.log('Badges enabled: ' + !!currentPermissions.badge);
    console.log('Sounds enabled: ' + !!currentPermissions.sound);
    console.log('Alerts enabled: ' + !!currentPermissions.alert);
});
```

198 199 200 201 202 203 204 205 206
### Android

The React-Native code equivalent on Android is:

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

// On Android, we allow for only one (global) listener per each event type.
NotificationsAndroid.setRegistrationTokenUpdateListener((deviceToken) => {
Raymond Penners's avatar
Raymond Penners committed
207
	console.log('Push-notifications registered!', deviceToken)
208 209 210 211 212 213
});

```

`deviceToken` being the token used to identify the device on the GCM.

Lidan Hifi's avatar
Lidan Hifi committed
214 215
---

216

Lidan Hifi's avatar
Lidan Hifi committed
217
## Handling Received Notifications
Lidan Hifi's avatar
Lidan Hifi committed
218

219 220
### iOS

Lidan Hifi's avatar
Lidan Hifi committed
221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236
When you receive a notification, the application can be in one of the following states:

1. **Forground**- When the app in running and is used by the user right now. in this case, `notificationReceivedForeground` event will be fired.
2. **Background**- When the app is running but in background state. in this case, `notificationReceivedBackground` event will be fired.
3. **Notification Opened**- When you open the notifications from the notification center. in this case, `notificationOpened` event will be fired.

Example:

```javascript
constructor() {
	NotificationsIOS.addEventListener('notificationReceivedForeground', this.onNotificationReceivedForeground.bind(this));
    NotificationsIOS.addEventListener('notificationReceivedBackground', this.onNotificationReceivedBackground.bind(this));
    NotificationsIOS.addEventListener('notificationOpened', this.onNotificationOpened.bind(this));
}

onNotificationReceivedForeground(notification) {
237
	console.log("Notification Received - Foreground", notification);
Lidan Hifi's avatar
Lidan Hifi committed
238 239 240
}

onNotificationReceivedBackground(notification) {
241
	console.log("Notification Received - Background", notification);
Lidan Hifi's avatar
Lidan Hifi committed
242 243 244
}

onNotificationOpened(notification) {
245
	console.log("Notification opened by device user", notification);
Lidan Hifi's avatar
Lidan Hifi committed
246 247 248 249 250 251 252 253 254 255
}

componentWillUnmount() {
	// Don't forget to remove the event listeners to prevent memory leaks!
	NotificationsIOS.removeEventListener('notificationReceivedForeground', this.onNotificationReceivedForeground.bind(this));
	NotificationsIOS.removeEventListener('notificationReceivedBackground', this.onNotificationReceivedBackground.bind(this));
	NotificationsIOS.removeEventListener('notificationOpened', this.onNotificationOpened.bind(this));
}
```

256
#### Notification Object
Lidan Hifi's avatar
Lidan Hifi committed
257 258 259 260 261 262 263 264 265
When you receive a push notification, you'll get an instance of `IOSNotification` object, contains the following methods:

- **`getMessage()`**- returns the notification's main message string.
- **`getSound()`**- returns the sound string from the `aps` object.
- **`getBadgeCount()`**- returns the badge count number from the `aps` object.
- **`getCategory()`**- returns the category from the `aps` object (related to interactive notifications).
- **`getData()`**- returns the data payload (additional info) of the notification.
- **`getType()`**- returns `managed` for managed notifications, otherwise returns `regular`.

266
#### Background Queue (Important!)
Lidan Hifi's avatar
Lidan Hifi committed
267 268 269 270 271
When a push notification is opened but the app is not running, the application will be in a **cold launch** state, until the JS engine is up and ready to handle the notification.
The application will collect the events (notifications, actions, etc.) that happend during the cold launch for you. 

When your app is ready (most of the time it's after the call to `requestPermissions()`), just call to `NotificationsIOS.consumeBackgroundQueue();` in order to consume the background queue. For more info see `index.ios.js` in the example app.

272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290
### Android

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

// On Android, we allow for only one (global) listener per each event type.
NotificationsAndroid.setNotificationReceivedListener((notification) => {
	console.log("Notification received on device", notification.getData());
});
NotificationsAndroid.setNotificationOpenedListener((notification) => {
	console.log("Notification opened by device user", notification.getData());
});
```

#### Notification Object
- **`getData()`**- content of the `data` section of the original message (sent to GCM).
- **`getTitle()`**- Convenience for returning `data.title`.
- **`getMessage()`**- Convenience for returning `data.body`.

Lidan Hifi's avatar
Lidan Hifi committed
291 292
---

293 294 295 296 297 298 299 300 301 302 303
## 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.

We provide a similar implementation on Android using `PendingNotifications.getInitialNotification()` which returns a promise:

```javascript
import {NotificationsAndroid, PendingNotifications} from 'react-native-notifications';

PendingNotifications.getInitialNotification()
  .then((notification) => {
Andrea Sessa's avatar
Andrea Sessa committed
304
  		console.log("Initial notification was:", (notification ? notification.getData() : 'N/A'));
305 306 307 308 309 310 311 312 313 314 315
	})  	
  .catch((err) => console.error("getInitialNotifiation() failed", err));

```

> 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.


Lidan Hifi's avatar
Lidan Hifi committed
316
## Triggering Local Notifications
Lidan Hifi's avatar
Lidan Hifi committed
317

318
### iOS
319

320
You can manually trigger local notifications in your JS code, to be posted immediately or in the future.
Lidan Hifi's avatar
Lidan Hifi committed
321 322 323 324 325
Triggering local notifications is fully compatible with React Native `PushNotificationsIOS` library.

Example:

```javascript
326
let localNotification = NotificationsIOS.localNotification({
Lidan Hifi's avatar
Lidan Hifi committed
327 328 329
	alertBody: "Local notificiation!",
	alertTitle: "Local Notification Title",
	soundName: "chime.aiff",
330
    silent: false,
Lidan Hifi's avatar
Lidan Hifi committed
331 332 333 334 335 336 337
	category: "SOME_CATEGORY",
	userInfo: { }
});
```

Notification object contains:

338
- **`fireDate`**- The date and time when the system should deliver the notification (optinal - default is immidiate dispatch).
Lidan Hifi's avatar
Lidan Hifi committed
339 340
- `alertBody`- The message displayed in the notification alert.
- `alertTitle`- The title of the notification, displayed in the notifications center.
341
- `alertAction`- The "action" displayed beneath an actionable notification on the lockscreen (e.g. "Slide to **open**"). Note that Apple no longer shows this in iOS 10.
342 343
- `soundName`- The sound played when the notification is fired (optional -- will play default sound if unspecified). This must be the filename of a sound included in the application bundle; the sound must be 30 seconds or less and should be encoded with linear PCM or IMA4.
- `silent`- Whether the notification sound should be suppressed (optional).
Lidan Hifi's avatar
Lidan Hifi committed
344
- `category`- The category of this notification, required for [interactive notifications](#interactive--actionable-notifications-ios-only) (optional).
Lidan Hifi's avatar
Lidan Hifi committed
345 346
- `userInfo`- An optional object containing additional notification data.

347 348 349 350 351 352 353 354 355 356 357 358 359 360
### Android

Much like on iOS, notifications can be triggered locally. The API to do so is a simplified version of the iOS equivalent that works more natually with the Android perception of push (remote) notifications:

```javascript
NotificationsAndroid.localNotification({
	title: "Local notification",
	body: "This notification was generated by the app!",
	extra: "data"
});
```

Upon notification opening (tapping by the device user), all data fields will be delivered as-is).

361 362 363
### Cancel Scheduled Local Notifications

The `NotificationsIOS.localNotification()` and `NotificationsAndroid.localNotification()` methods return unique `notificationId` values, which can be used in order to cancel specific local notifications that were scheduled for delivery on `fireDate` and have not yet been delivered. You can cancel local notification by calling `NotificationsIOS.cancelLocalNotification(notificationId)` or `NotificationsAndroid.cancelLocalNotification(notificationId)`.
364

365
Example (iOS):
366 367 368 369 370 371 372 373 374 375 376 377 378

```javascript
let someLocalNotification = NotificationsIOS.localNotification({
	alertBody: "Local notificiation!",
	alertTitle: "Local Notification Title",
	soundName: "chime.aiff",
	category: "SOME_CATEGORY",
	userInfo: { }
});

NotificationsIOS.cancelLocalNotification(someLocalNotification);
```

379
To cancel all local notifications (**iOS only!**), use `cancelAllLocalNotifications()`:
380 381 382 383 384

```javascript
NotificationsIOS.cancelAllLocalNotifications();
```

385 386 387 388 389 390 391 392 393 394 395 396 397 398
### Cancel Delivered Local Notifications (iOS 10+ only)

To dismiss notifications from the notification center that have already been shown to the user, call `NotificationsIOS.removeDeliveredNotifications([notificationId])`:

```javascript
let someLocalNotification = NotificationsIOS.localNotification({...});

NotificationsIOS.removeDeliveredNotifications([someLocalNotification]);
```

Call `removeAllDeliveredNotifications()` to dismiss all delivered notifications
(note that this will dismiss push notifications in addition to local
notifications).

Lidan Hifi's avatar
Lidan Hifi committed
399 400 401
---

## Managed Notifications (iOS only)
Lidan Hifi's avatar
Lidan Hifi committed
402

Lidan Hifi's avatar
Lidan Hifi committed
403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457
Managed notifications are notifications that can be cleared by a server request.
You can find this feature in facebook messenger, when you receive a message in your mobile, but open it in facebook web. More examples are Whatsapp web and gmail app.

In order to handle managed notifications, your app must support background notifications, and the server should send the notifications you'd like to "manage" a bit differently. Let's start.

First, enable the *Remote notifications* checkbox under **capabilities - Background Modes**:
![Background Modes](http://docs.urbanairship.com/_images/ios-background-push-capabilities1.png)

Then, add the following lines to `info.plist`:

```xml
<key>UIBackgroundModes</key>
<array>
	<string>remote-notification</string>
</array>
```

That's it for the client side!

Now the server should push the notification a bit differently- background instead of reguler. You should also provide the action (`CREATE` notification or `CLEAR` notification), and `notificationId` as a unique identifier of the notification.

**Regular** notification payload:

```javascript
{
  aps: {
    alert: {
      body: "This is regular notification"
	},
	badge: 5,
	sound: "chime.aiff",
  }
}
```

**Managed** notification payload:

```javascript
{
  aps: {
  	"content-available": 1
  },
  managedAps: {
    action: "CREATE", // set it to "CLEAR" in order to clear the notification remotely
    notificationId: "1234", // must be unique identifier
    sound: "chime.aiff",
    alert: {
      body: "This is managed notification"
    }
  }
}
```

---

458 459 460 461
## Remove notifications (iOS only)

### getDeliveredNotifications

462
`PushNotification.getDeliveredNotifications(callback: (notifications: Array<Object>) => void)` 
463 464 465 466 467

Provides you with a list of the app’s notifications that are still displayed in Notification Center.

### removeDeliveredNotifications

468
`PushNotification.removeDeliveredNotifications(identifiers: Array<String>)` 
469 470 471 472 473 474 475 476 477 478 479

Removes the specified notifications from Notification Center.

### removeAllDeliveredNotifications

`PushNotification.removeAllDeliveredNotifications()` 

Removes all delivered notifications from Notification Center.

---

Lidan Hifi's avatar
Lidan Hifi committed
480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524
## PushKit API (iOS only)

The PushKit framework provides the classes for your iOS apps to receive background pushes from remote servers. it has better support for background notifications compared to regular push notifications with `content-available: 1`. More info in [iOS PushKit documentation](https://developer.apple.com/library/ios/documentation/NetworkingInternet/Reference/PushKit_Framework/).

### Register to PushKit
After [preparing your app to receive VoIP push notifications](https://developer.apple.com/library/ios/documentation/Performance/Conceptual/EnergyGuide-iOS/OptimizeVoIP.html), add the following lines to `appDelegate.m` in order to support PushKit events:

```objective-c
#import "RNNotifications.h"
#import <PushKit/PushKit.h>
``` 

And the following methods:

```objective-c
// PushKit API Support
- (void)pushRegistry:(PKPushRegistry *)registry didUpdatePushCredentials:(PKPushCredentials *)credentials forType:(NSString *)type
{
  [RNNotifications didUpdatePushCredentials:credentials forType:type];
}

- (void)pushRegistry:(PKPushRegistry *)registry didReceiveIncomingPushWithPayload:(PKPushPayload *)payload forType:(NSString *)type
{
  [RNNotifications didReceiveRemoteNotification:payload.dictionaryPayload];
}
```

In your ReactNative code, add event handler for `pushKitRegistered` event and call to `registerPushKit()`:

```javascript
constructor() {
	NotificationsIOS.addEventListener('pushKitRegistered', this.onPushKitRegistered.bind(this));
    NotificationsIOS.registerPushKit();
}

onPushKitRegistered(deviceToken) {
	console.log("PushKit Token Received: " + deviceToken);
}

componentWillUnmount() {
	// Don't forget to remove the event listeners to prevent memory leaks!
	NotificationsIOS.removeEventListener('pushKitRegistered', onPushKitRegistered(this));
}
```

Lidan Hifi's avatar
Lidan Hifi committed
525 526
> 1. Notice that PushKit device token and regular notifications device token are different, so you must handle two different tokens in the server side in order to support this feature.
> 2. PushKit will not request permissions from the user for push notifications.
Lidan Hifi's avatar
Lidan Hifi committed
527 528 529 530


---

531 532 533
## Interactive / Actionable Notifications

> This section provides description for iOS. For notifications customization on Android, refer to [our wiki](https://github.com/wix/react-native-notifications/wiki/Android-Customizations#customizing-notifications-layout).
Lidan Hifi's avatar
Lidan Hifi committed
534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570

Interactive notifications allow you to reply to a message right from the notification banner or take action right from the lock screen. 

On the Lock screen and within Notification Center, you swipe from right to left 
to reveal actions. Destructive actions, like trashing an email, are color-coded red. Relatively neutral actions, like dismissing an alert or declining an invitation, are color-coded gray.

For banners, you pull down to reveal actions as buttons. For popups, the actions are immediately visible — the buttons are right there.

You can find more info about interactive notifications [here](http://www.imore.com/interactive-notifications-ios-8-explained).

![Interactive Notifications](http://i.imgur.com/XrVzy9w.gif)


Notification **actions** allow the user to interact with a given notification.

Notification **categories** allow you to group multiple actions together, and to connect the actions with the push notification itself.

In order to support interactive notifications, firstly add the following methods to `appDelegate.m` file:

```objective-c
// Required for the notification actions.
- (void)application:(UIApplication *)application handleActionWithIdentifier:(NSString *)identifier forLocalNotification:(UILocalNotification *)notification withResponseInfo:(NSDictionary *)responseInfo completionHandler:(void (^)())completionHandler
{
  [RNNotifications handleActionWithIdentifier:identifier forLocalNotification:notification withResponseInfo:responseInfo completionHandler:completionHandler];
}

- (void)application:(UIApplication *)application handleActionWithIdentifier:(NSString *)identifier forRemoteNotification:(NSDictionary *)userInfo withResponseInfo:(NSDictionary *)responseInfo completionHandler:(void (^)())completionHandler
{
  [RNNotifications handleActionWithIdentifier:identifier forRemoteNotification:userInfo withResponseInfo:responseInfo completionHandler:completionHandler];
}
```

Then, follow the basic workflow of adding interactive notifications to your app:

1. Config the actions.
2. Group actions together into categories.
3. Register to push notifications with the configured categories.
Lidan Hifi's avatar
Lidan Hifi committed
571
4. Push a notification (or trigger a [local](#triggering-local-notifications) one) with the configured category name.
Lidan Hifi's avatar
Lidan Hifi committed
572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636

### Example
#### Config the Actions
We will config two actions: upvote and reply.

```javascript
import NotificationsIOS, { NotificationAction, NotificationCategory } from 'react-native-notifications';

let upvoteAction = new NotificationAction({
  activationMode: "background",
  title: String.fromCodePoint(0x1F44D),
  identifier: "UPVOTE_ACTION"
}, (action, completed) => {
  console.log("ACTION RECEIVED");
  console.log(JSON.stringify(action));

  // You must call to completed(), otherwise the action will not be triggered
  completed();
});

let replyAction = new NotificationAction({
  activationMode: "background",
  title: "Reply",
  behavior: "textInput",
  authenticationRequired: true,
  identifier: "REPLY_ACTION"
}, (action, completed) => {
  console.log("ACTION RECEIVED");
  console.log(action);

  completed();
});

```

#### Config the Category
We will group `upvote` action and `reply` action into a single category: `EXAMPLE_CATEGORY `. If the notification contains `EXAMPLE_CATEGORY ` under `category` field, those actions will appear.

```javascript
let exampleCategory = new NotificationCategory({
  identifier: "EXAMPLE_CATEGORY",
  actions: [upvoteAction, replyAction],
  context: "default"
});
```

#### Register to Push Notifications
Instead of basic registration like we've done before, we will register the device to push notifications with the category we've just created.

```javascript
NotificationsIOS.requestPermissions([exampleCategory]);
```

#### Push an Interactive Notification
Notification payload should look like this:

```javascript
{
  aps: {
	// ... (alert, sound, badge, etc)
	category: "EXAMPLE_CATEGORY"
  }
}
```

Lidan Hifi's avatar
Lidan Hifi committed
637
The [example app](https://github.com/wix/react-native-notifications/tree/master/example) contains this interactive notification example, you can follow there.
Lidan Hifi's avatar
Lidan Hifi committed
638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657

### `NotificationAction` Payload

- `title` - Action button title.
- `identifier` - Action identifier (must be unique).
- `activationMode` - Indicating whether the app should activate to the foreground or background.
	- `foreground` (default) - Activate the app and put it in the foreground.
	- `background` - Activate the app and put it in the background. If the app is already in the foreground, it remains in the foreground.
- `behavior` - Indicating additional behavior that the action supports.
	- `default` - No additional behavior.
	- `textInput` - When button is tapped, the action opens a text input. the text will be delivered to your action callback.
- `destructive` - A Boolean value indicating whether the action is destructive. When the value of this property is `true`, the system displays the corresponding button differently to indicate that the action is destructive.
- `authenticationRequired` - A Boolean value indicating whether the user must unlock the device before the action is performed.

### `NotificationCategory` Payload

- `identifier` - The name of the action group (must be unique).
- `actions` - An array of `NotificationAction` objects, which related to this category.
- `context` - Indicating the amount of space available for displaying actions in a notification.
	- `default` (default) - Displayes up to 4 actions (full UI).
Lidan Hifi's avatar
Lidan Hifi committed
658 659 660
	- `minimal` - Displays up tp 2 actions (minimal UI).

	
661 662 663 664 665 666 667 668 669 670
#### Set application icon badges count (iOS only) 

Set to specific number: 
```javascript
NotificationsIOS.setBadgesCount(2);
```
Clear badges icon:
```javascript
NotificationsIOS.setBadgesCount(0);
```
Lidan Hifi's avatar
Lidan Hifi committed
671 672 673
## License
The MIT License.

Marc Sommerhalder's avatar
Marc Sommerhalder committed
674
See [LICENSE](LICENSE)