Commit fe30ae5e authored by Amit Davidi's avatar Amit Davidi

Break README into sub-sections in separate files with a ToC

parent 83d1386e
This diff is collapsed.
This diff is collapsed.
# Installation
As with any React Native project, the first step is to add the project as an npm dependency.
The 2nd is to do some platform specific setup so as to be able to work with Apple and Google's services for push notifications.
Start by running this:
```
$ npm install react-native-notifications --save
```
## <img src="https://upload.wikimedia.org/wikipedia/commons/thumb/f/fa/Apple_logo_black.svg/2000px-Apple_logo_black.svg.png" width=30/> iOS
First, [Manually link](https://facebook.github.io/react-native/docs/linking-libraries-ios.html#manual-linking) the library to your Xcode project.
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];
}
- (void)application:(UIApplication *)application didFailToRegisterForRemoteNotificationsWithError:(NSError *)error {
[RNNotifications didFailToRegisterForRemoteNotificationsWithError:error];
}
// 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];
}
```
## <img src="https://upload.wikimedia.org/wikipedia/commons/thumb/a/a0/APK_format_icon.png/768px-APK_format_icon.png" width=30/> Android
Add a reference to the library's native code in your global `settings.gradle`:
```gradle
include ':reactnativenotifications'
project(':reactnativenotifications').projectDir = new File(rootProject.projectDir, '../node_modules/react-native-notifications/android')
```
Declare the library as a dependency in your **app-project's** `build.gradle`:
```gradle
dependencies {
// ...
compile project(':reactnativenotifications')
}
```
Add the library to your application class (e.g. `MainApplication.java`):
```java
import com.wix.reactnativenotifications.RNNotificationsPackage;
...
@Override
protected List<ReactPackage> getPackages() {
return Arrays.<ReactPackage>asList(
new MainReactPackage(),
// ...
// Add this line:
new RNNotificationsPackage(MainApplication.this)
);
```
### Receiving push notifications
> Note: This section is only necessary in case you wish to be able to **receive** push notifications in your React-Native app.
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.
#### Step #1: Subscribe to Google's GCM
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.
Alternatively, follow [Google's complete guide](https://developers.google.com/cloud-messaging/android/client#create-an-api-project).
#### Step #2: Add Sender ID to Manifest File
Once obtained, bundle the Sender ID onto your main `manifest.xml` file:
```gradle
<manifest>
...
<application>
...
// Replace '1234567890' with your sender ID.
// IMPORTANT: Leave the trailing \0 intact!!!
<meta-data android:name="com.wix.reactnativenotifications.gcmSenderId" android:value="1234567890\0"/>
</application>
</manifest>
```
# Local Notifications
## <img src="https://upload.wikimedia.org/wikipedia/commons/thumb/f/fa/Apple_logo_black.svg/2000px-Apple_logo_black.svg.png" width=30/> iOS
You can manually trigger local notifications in your JS code, to be posted immediately or in the future.
Triggering local notifications is fully compatible with React Native `PushNotificationsIOS` library.
Example:
```javascript
let localNotification = NotificationsIOS.localNotification({
alertBody: "Local notificiation!",
alertTitle: "Local Notification Title",
soundName: "chime.aiff",
silent: false,
category: "SOME_CATEGORY",
userInfo: { }
});
```
Notification object contains:
- **`fireDate`**- The date and time when the system should deliver the notification (optinal - default is immidiate dispatch).
- `alertBody`- The message displayed in the notification alert.
- `alertTitle`- The title of the notification, displayed in the notifications center.
- `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.
- `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).
- `category`- The category of this notification, required for [interactive notifications](#interactive--actionable-notifications-ios-only) (optional).
- `userInfo`- An optional object containing additional notification data.
### 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)`.
Example:
```javascript
let someLocalNotification = NotificationsIOS.localNotification({
alertBody: "Local notificiation!",
alertTitle: "Local Notification Title",
soundName: "chime.aiff",
category: "SOME_CATEGORY",
userInfo: { }
});
NotificationsIOS.cancelLocalNotification(someLocalNotification);
```
To cancel all local notifications (**iOS only!**), use `cancelAllLocalNotifications()`:
```javascript
NotificationsIOS.cancelAllLocalNotifications();
```
#### 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).
## <img src="https://upload.wikimedia.org/wikipedia/commons/thumb/a/a0/APK_format_icon.png/768px-APK_format_icon.png" width=30/> 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).
# Handling Notification 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 `notificationReceivedForeground` event will be fired.
2. **Background:** When the app is running in a background state; in this case, a `notificationReceivedBackground` event will be fired.
Finally, when a notification is _opened_ by the device user (i.e. tapped-on), a `notificationOpened` event is 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) {
console.log("Notification Received - Foreground", notification);
}
onNotificationReceivedBackground(notification) {
console.log("Notification Received - Background", notification);
}
onNotificationOpened(notification) {
console.log("Notification opened by device user", notification);
}
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));
}
```
### Notification Object
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`.
### Background Queue (Important - please read!)
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.
## <img src="https://upload.wikimedia.org/wikipedia/commons/thumb/a/a0/APK_format_icon.png/768px-APK_format_icon.png" width=30/> Android
On Android the same core functionality is provided, but using a different API:
```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`.
## Querying initial notification (Android)
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.
While for iOS we nonetheless offer the more elaborate _Background Queue_ solution, on Android we've settled for an implementation similar to React Native's -- An API method `PendingNotifications.getInitialNotification()`, which returns a promise:
```javascript
import {NotificationsAndroid, PendingNotifications} from 'react-native-notifications';
PendingNotifications.getInitialNotification()
.then((notification) => {
console.log("Initial notification was:", (notification ? notification.getData() : '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.
# Push Notifications Subscription
The typical flow for subscribing a device for receiving push notification in real time is to first register the device at the vendor's servers (e.g. GCM), then publishing the received token to your own push management servers.
This section is about the first part of the flow.
## <img src="https://upload.wikimedia.org/wikipedia/commons/thumb/f/fa/Apple_logo_black.svg/2000px-Apple_logo_black.svg.png" width=30/> iOS
In order to handle notifications, you must register the `remoteNotificationsRegistered` event beforehand.
In your React Native app:
```javascript
import NotificationsIOS from 'react-native-notifications';
class App extends Component {
constructor() {
NotificationsIOS.addEventListener('remoteNotificationsRegistered', this.onPushRegistered.bind(this));
NotificationsIOS.addEventListener('remoteNotificationsRegistrationFailed', this.onPushRegistrationFailed.bind(this));
NotificationsIOS.requestPermissions();
}
onPushRegistered(deviceToken) {
// TODO: Send the token to my server so it could send back push notifications...
console.log("Device Token Received", deviceToken);
}
onPushRegistrationFailed(error) {
// For example:
//
// error={
// domain: 'NSCocoaErroDomain',
// code: 3010,
// localizedDescription: 'remote notifications are not supported in the simulator'
// }
console.error(error);
}
componentWillUnmount() {
// prevent memory leaks!
NotificationsIOS.removeEventListener('remoteNotificationsRegistered', this.onPushRegistered.bind(this));
NotificationsIOS.removeEventListener('remoteNotificationsRegistrationFailed', this.onPushRegistrationFailed.bind(this));
}
}
```
When you have the device token, POST it to your server and register the device in your notifications provider (Amazon SNS, Azure, etc.).
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);
});
```
## <img src="https://upload.wikimedia.org/wikipedia/commons/thumb/a/a0/APK_format_icon.png/768px-APK_format_icon.png" width=30/> Android
Android works similarly but using a different API; The equivalent code is:
```javascript
import {NotificationsAndroid} from 'react-native-notifications';
// On Android, we allow for only one (global) listener per each event type.
NotificationsAndroid.setRegistrationTokenUpdateListener((deviceToken) => {
// TODO: Send the token to my server so it could send back push notifications...
console.log('Push-notifications registered!', deviceToken)
});
```
`deviceToken` being the token used to identify the device on the GCM.
Markdown is supported
0%
or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment