Commit d94ebbb8 authored by yogevbd's avatar yogevbd

Fix handling actions, Add event handling documentation guide

parent 6d3ebcce
...@@ -13,7 +13,7 @@ Notifications.registerRemoteNotifications(); ...@@ -13,7 +13,7 @@ Notifications.registerRemoteNotifications();
``` ```
## getInitialNotification() ## getInitialNotification()
This method returns a promise. If the app was launched by a push notification, this promise resolves to an object of type [Notification](http://localhost:3000/react-native-notifications/docs/notification-object). Otherwise, it resolves to undefined. This method returns a promise. If the app was launched by a push notification, this promise resolves to an object of type [Notification](notification-object). Otherwise, it resolves to undefined.
```js ```js
const notification: Notification = await Notifications.getInitialNotification(); const notification: Notification = await Notifications.getInitialNotification();
......
...@@ -14,7 +14,7 @@ Notifications.events().registerRemoteNotificationsRegistered((event: Registered) ...@@ -14,7 +14,7 @@ Notifications.events().registerRemoteNotificationsRegistered((event: Registered)
``` ```
## registerNotificationReceived() ## registerNotificationReceived()
Fired when a remote notification is received in foreground state. The handler will be invoked with an instance of [Notification](http://localhost:3000/react-native-notifications/docs/notification-object). Fired when a remote notification is received in foreground state. The handler will be invoked with an instance of [Notification](notification-object).
Should call completion function on iOS, will be ignored on Android. Should call completion function on iOS, will be ignored on Android.
```js ```js
...@@ -27,7 +27,7 @@ Notifications.events().registerNotificationReceived((notification: Notification, ...@@ -27,7 +27,7 @@ Notifications.events().registerNotificationReceived((notification: Notification,
``` ```
## registerRemoteNotificationOpened() ## registerRemoteNotificationOpened()
Fired when a remote notification is opened from dead or background state. The handler will be invoked with an instance of [Notification](http://localhost:3000/react-native-notifications/docs/notification-object). Fired when a remote notification is opened from dead or background state. The handler will be invoked with an instance of [Notification](notification-object).
Should call completion function on iOS, will be ignored on Android. Should call completion function on iOS, will be ignored on Android.
```js ```js
......
...@@ -6,6 +6,11 @@ sidebar_label: Notification ...@@ -6,6 +6,11 @@ sidebar_label: Notification
Contains the payload data. Contains the payload data.
- **`message`**- returns the notification's main message string.
- **`sound`**- returns the sound string from the `aps` object.
- **`badge`**- returns the badge count number from the `aps` object.
- **`category`**- returns the category from the `aps` object (related to interactive notifications).
- **`data`**- returns the data payload (additional info) of the notification.
Example: Example:
```js ```js
......
---
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.
...@@ -39,7 +39,7 @@ class NotificationsExampleApp extends Component { ...@@ -39,7 +39,7 @@ class NotificationsExampleApp extends Component {
} }
requestPermissions() { requestPermissions() {
Notifications.ios.requestPermissions(); Notifications.registerRemoteNotifications();
} }
setCategories() { setCategories() {
......
...@@ -30,7 +30,7 @@ ...@@ -30,7 +30,7 @@
- (void)didReceiveNotificationResponse:(UNNotificationResponse *)response completionHandler:(void (^)(void))completionHandler { - (void)didReceiveNotificationResponse:(UNNotificationResponse *)response completionHandler:(void (^)(void))completionHandler {
[_store setActionCompletionHandler:completionHandler withCompletionKey:response.notification.request.identifier]; [_store setActionCompletionHandler:completionHandler withCompletionKey:response.notification.request.identifier];
[RNEventEmitter sendEvent:RNNotificationOpened body:[RNNotificationParser parseNotification:response.notification]]; [RNEventEmitter sendEvent:RNNotificationOpened body:[RNNotificationParser parseNotificationResponse:response]];
} }
@end @end
...@@ -56,7 +56,7 @@ export class NotificationsRoot { ...@@ -56,7 +56,7 @@ export class NotificationsRoot {
/** /**
* getInitialNotification * getInitialNotification
*/ */
public getInitialNotification(): Promise<Notification> { public getInitialNotification(): Promise<Notification | undefined> {
return this.commands.getInitialNotification(); return this.commands.getInitialNotification();
} }
......
...@@ -3,6 +3,7 @@ import { ...@@ -3,6 +3,7 @@ import {
Registered, RegistrationError, RegisteredPushKit Registered, RegistrationError, RegisteredPushKit
} from '../interfaces/NotificationEvents'; } from '../interfaces/NotificationEvents';
import { Notification } from '../DTO/Notification'; import { Notification } from '../DTO/Notification';
import { NotificationActionResponse } from '../interfaces/NotificationActionResponse';
export class NativeEventsReceiver { export class NativeEventsReceiver {
private emitter: EventEmitter; private emitter: EventEmitter;
...@@ -28,9 +29,10 @@ export class NativeEventsReceiver { ...@@ -28,9 +29,10 @@ export class NativeEventsReceiver {
return this.emitter.addListener('pushKitNotificationReceived', callback); return this.emitter.addListener('pushKitNotificationReceived', callback);
} }
public registerRemoteNotificationOpened(callback: (response: Notification, completion: () => void) => void): EmitterSubscription { public registerRemoteNotificationOpened(callback: (notification: Notification, completion: () => void, actionResponse?: NotificationActionResponse) => void): EmitterSubscription {
return this.emitter.addListener('notificationOpened', (payload, completion) => { return this.emitter.addListener('notificationOpened', (response, completion) => {
callback(new Notification(payload), completion); const action = response.action ? new NotificationActionResponse(response.action) : undefined
callback(new Notification(response.notification), completion, action);
}); });
} }
......
...@@ -9,7 +9,7 @@ export class Commands { ...@@ -9,7 +9,7 @@ export class Commands {
constructor( constructor(
private readonly nativeCommandsSender: NativeCommandsSender, private readonly nativeCommandsSender: NativeCommandsSender,
private readonly uniqueIdProvider: UniqueIdProvider private readonly uniqueIdProvider: UniqueIdProvider
) {} ) { }
public postLocalNotification(notification: Notification, id?: number) { public postLocalNotification(notification: Notification, id?: number) {
const notificationId: number = id ? id : this.uniqueIdProvider.generate(); const notificationId: number = id ? id : this.uniqueIdProvider.generate();
...@@ -17,9 +17,13 @@ export class Commands { ...@@ -17,9 +17,13 @@ export class Commands {
return result; return result;
} }
public async getInitialNotification(): Promise<Notification> { public async getInitialNotification(): Promise<Notification | undefined> {
return this.nativeCommandsSender.getInitialNotification().then((payload) => { return this.nativeCommandsSender.getInitialNotification().then((payload) => {
return new Notification(payload); if (payload) {
return new Notification(payload);
}
return undefined;
}); });
} }
......
export interface NotificationActionResponse { export class NotificationActionResponse {
identifier: string; identifier: string;
text: string; text?: string;
constructor(response: any) {
this.identifier = response.identifier;
this.text = response.text;
}
} }
...@@ -45,6 +45,10 @@ ...@@ -45,6 +45,10 @@
"title": "Notification object", "title": "Notification object",
"sidebar_label": "Notification" "sidebar_label": "Notification"
}, },
"notifications-events": {
"title": "Handling Notification Events",
"sidebar_label": "Events"
},
"subscription": { "subscription": {
"title": "Push Notifications Subscription", "title": "Push Notifications Subscription",
"sidebar_label": "Subscription" "sidebar_label": "Subscription"
......
{ {
"docs": { "docs": {
"Installation": ["installation-ios", "installation-android"], "Installation": ["installation-ios", "installation-android"],
"Guides": ["subscription", "localNotifications"], "Guides": ["subscription", "notifications-events", "localNotifications"],
"Advanced": ["advanced-ios"] "Advanced": ["advanced-ios"]
}, },
"api": { "api": {
......
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