Giter Site home page Giter Site logo

react-native-ios-notification-actions's Introduction

looking for a maintainer

I'm not actively maintaining this, so use it at your own risk and make sure to check the open issues.

If you're interested in maintaining this repo, drop me a line at: hello(at)alonso.io

react-native-ios-notification-actions

locked unlocked

tl;dr

Notification Actions allow the user to interact with the push notification. Those shiny buttons that show up when you swipe a notification to the left on your lock screen, or pull down a notification that appears on the top of the screen? Each one of those buttons is an action.

Notification Categories allow you to group multiple actions together. This Category is what you'll ultimately associate with a push notification.

The basic workflow is:

  1. Create and configure some actions.
  2. Group them together into a category.
  3. (optional) Implement some appdelegate methods to respond to actions.
  4. Show a local (or remote) notification, and associate it with the category from (2) to show your actions.

Install

rnpm (preferred)

`rnpm install react-native-ios-notification-actions

Manual

  1. `npm install react-native-ios-notification-actions
  2. Drag ./RNNotificationActions/RNNotificationActions.xcodeproj into your project.
  3. Add libRNNotificationActions.a to your Link Binary With Libraries build phase

Getting Started

  1. Follow the instructions here to set up push notifications in your app.
  2. In AppDelegate.m:
// Import 'RNNotificationActions.h' at top.
#import "RNNotificationActions.h"

// Add support for push notification actions (optional)
- (void)application:(UIApplication *)application handleActionWithIdentifier:(nullable NSString *)identifier forLocalNotification:(nonnull UILocalNotification *)notification withResponseInfo:(nonnull NSDictionary *)responseInfo completionHandler:(nonnull void (^)())completionHandler
{
    NSLog(@"got local notification!");
    [RNNotificationActions application:application handleActionWithIdentifier:identifier forLocalNotification:notification withResponseInfo:responseInfo completionHandler:completionHandler];
}
- (void)application:(UIApplication *)application handleActionWithIdentifier:(NSString *)identifier forRemoteNotification:(NSDictionary *)userInfo withResponseInfo:(NSDictionary *)responseInfo completionHandler:(void (^)())completionHandler
{
  [RNNotificationActions application:application handleActionWithIdentifier:identifier forRemoteNotification:userInfo withResponseInfo:responseInfo completionHandler:completionHandler];
}

Example

import NotificationActions from 'react-native-ios-notification-actions'

// Create an "upvote" action that will display a button when a notification is swiped
let upvoteButton = new NotificationActions.Action({
  activationMode: 'background',
  title: 'Upvote',
  identifier: 'UPVOTE_ACTION'
}, (res, done) => {
  console.info('upvote button pressed with result: ', res);
  done(); //important!
});

// Create a "comment" button that will display a text input when the button is pressed
let commentTextButton = new NotificationActions.Action({
  activationMode: 'background',
  title: 'Reply',
  behavior: 'textInput',
  identifier: 'REPLY_ACTION'
}, (res, done) => {
  console.info('reply typed via notification from source: ', res.source, ' with text: ', res.text);
  done(); //important!
});

// Create a category containing our two actions
let myCategory = new NotificationActions.Category({
  identifier: 'something_happened',
  actions: [upvoteButton, commentTextButton],
  forContext: 'default'
});

// ** important ** update the categories
NotificationActions.updateCategories([myCategory]);

Then, when you present a local notification, you can simply use the same category name:

import {PushNotificationIOS} from 'react-native';

// Lock your screen before 5 seconds elapse!
setTimeout(() => {
    console.info('presenting local notification!');
    PushNotificationIOS.presentLocalNotification({
        alertBody: 'This is a local notification!',
        category: 'something_happened'
    });
}, 5000);

The same goes for remote notifications - just include {category: "your_category_name"} in your push notification payload.

Action options

  • title - [String] Title for the action button [apple doc]
  • identifier - [String] Identifier for the action.
  • onComplete - [function(responseData, completionHandler)] Called when the your app has been activated by the user interacting with this action. responseData contains inputted text if behavior is set to textInput. Important - you must call completionHandler when you are done handling the action.
  • behavior - [String] Custom behavior for the action [apple doc]
    • default (default) - No additional behaviors
    • textInput - When tapped, this action opens a text input. On completion, the text is delivered to your onComplete callback.
  • activationMode - [String] What should iOS do with this app when this action is pressed? [apple doc]
    • foreground (default) - Bring the app into the foreground
    • background - Launch the app in the background
  • authenticationRequired - [Boolean] Should the user be required to unlock the device before the action is performed? [apple doc]
  • destructive - [Boolean] If true, displays the action button differently (for example, colored red). [apple doc]

Category options

  • identifier - [String] Identifier for the category. When creating a local or remote notification, use this value to associate this category with that notification. [apple doc]
  • actions - [Array of Actions] The actions to display with this category. Maximum length depends on the value of the context property. [apple doc]
  • context - [String] Controls how many actions to display with a notification. [apple doc]
    • default (default) - Displays up to 4 actions.
    • minimal - Displays up to 2 actions.

TODO / help wanted

  • implement action parameters
  • PR react-native to allow "category" key in local notification payloads (and maybe other keys as well)

More info

Nice overview of interactive notifications

react-native-ios-notification-actions's People

Contributors

benhughes avatar holmesal avatar irfaan avatar oblador avatar varungupta85 avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar

react-native-ios-notification-actions's Issues

New Update

It will be a new version of the lib with pod setup file?

Invalid directory error

Hi! Hitting the following:

uncaught error Error: UnableToResolveError: Unable to resolve module react-native-notification-actions from /[path]/index.ios.js: Invalid directory /Users/node_modules/react-native-notification-actions

React seems to be looking for the module in Users/node_modules/react-native-notification-actions, when it is of course in [path]/node_modules/react-native-notification-actions

RN 0.18.0-rc

Any ideas?

Thanks! Looking forward to using (and hopefully contributing) to your module!

fetch when no active app state

fetch no working. When app in background, fetch work well. How can I send data to server when app no active?
`let approveButton = new NotificationActions.Action({
activationMode: 'background',
title: 'APPROVE',
identifier: 'APPROVE_ACTION'
}, (res, done) => {
fetch('https://test.ru/test');

    done(); //important!
});`

updateCategories deletes existing categories

I use react-native-ua for connection with Urban Airship. It has 32 pre-defined action categories out of the box.

It looks like updateCategories erases these categories, so I can not use them. Also, when the app receives a local push with actions, it begins to generate device tokens infinitely like in #14 .

Should Obj-C completion handler wait for JS?

On the Obj-C side, completion handlers are currently called immediately after the app event has been sent over the bridge. I haven't come up against any cases where this was disadvantageous, but I'm also not doing anything serious like fetching something over the network.

If this turns out the be a problem - an alternative implementation would be to store the obj-c completion handlers (no idea how to do this) by id, and pass that id over the bridge so that they can be invoked when the user calls done().

Access notification object in the onComplete handler for actions

Is there a way to access the notification object in the onComplete handler for the actions? I have an app where user can enter tasks for some other user. The other user will receive a push notification when a task is entered for him and I want to present two actions in the notification - Accept and Reject. On choosing any of the actions, I want to update the state of the task in the database such that creator knows that user has accepted or rejected the task. I need the taskId in order to update the task in the database which is present in the notification object but I didn't find a way to access the notification object in the onComplete handler in the documentation. Please let me know if it is possible. Thanks.

Not able to see notification actions using the example project

I am not able to see the notification actions using the example project in the repo. Below are the steps that I followed:

  1. Clone the repo
  2. Run npm install in the example directory
  3. Run rnpm link
  4. Open the xcode project in xcode
  5. Run the application in simulator
  6. I see the notification but when I swipe to the left, I only see a cross button and no actions.

What do I need to do in order to see the actions?

Thanks!

Unfortunately this is no longer working, can you provide some insight?

Hello,
Absolutely love the idea of this package but it unfortunately no longer works. Your update categories is calling to register the app, whcih is call the registration events, which your app is listening to so that it can again register the app - therefore we have ourselves an endless loop :(

From what I can tell, this would have been broken sinc eReact Native version 0.17 when they started emitting the loop

RCT_EXPORT_METHOD(updateCategories:(NSArray *)json)
{
    NSMutableArray *categories = [[NSMutableArray alloc] init];
    // Create the category
    for (NSDictionary *categoryJSON in json) {
        [categories addObject:[self categoryFromJSON:categoryJSON]];
    }

    // Get the current types
    UIUserNotificationSettings *settings;
    UIUserNotificationType types = settings.types;

    NSLog(@"Settings: %@", settings);
    // Update the settings for these types
    [[UIApplication sharedApplication] registerUserNotificationSettings:[UIUserNotificationSettings settingsForTypes:types categories:[NSSet setWithArray:categories]]];
}

in the code above at the end you are calling: [[UIApplication sharedApplication] registerUserNotificationSettings:[UIUserNotificationSettings settingsForTypes:types categories:[NSSet setWithArray:categories]]];

React's official implementation listens to changes to this value:

// Required to register for notifications
- (void)application:(UIApplication *)application didRegisterUserNotificationSettings:(UIUserNotificationSettings *)notificationSettings
{
  NSLog(@"Register Push!");
  [RCTPushNotificationManager didRegisterUserNotificationSettings:notificationSettings];
}

As you can see here it is then emitting the didRegister command...

This then calls the paired part in React Native's push notification implementation:

+ (void)didRegisterUserNotificationSettings:(__unused UIUserNotificationSettings *)notificationSettings
{
  if ([UIApplication instancesRespondToSelector:@selector(registerForRemoteNotifications)]) {
    NSLog(@"REGISTER NOW!");
    [[UIApplication sharedApplication] registerForRemoteNotifications];
  }
}

It would appear the "if" is always true because REGISTER NOW loops as well.

This emits this function:

- (void)handleRemoteNotificationsRegistered:(NSNotification *)notification
{
  NSLog(@"Remote Notifications Registered: %@", notification);
  [_bridge.eventDispatcher sendDeviceEventWithName:@"remoteNotificationsRegistered"
                                              body:notification.userInfo];
}

which then emits the registration event which is being listened to by updateCategories:

NativeAppEventEmitter.addListener('remoteNotificationsRegistered', () => {
    console.info('updating notification categories in response to permission change');
    RNNotificationActions.updateCategories(cats);
  });

and thus, the loop continues, indefinitely.

image

handleActionWithIdentifier not firing when app is not running (i.e. force-quit).

handleActionWithIdentifier works perfectly when app is backgrounded, but as soon as the app is killed/force-quit, actions on push notifications go silently, appearing not to trigger [RNNotificationActions application:application handleActionWithIdentifier:identifier forRemoteNotification:userInfo withResponseInfo:responseInfo completionHandler:completionHandler]; at all.

Performing a task within the handleActionWithIdentifier declaration works fine (i.e. not sending a notification over the bridge to react-native).

I have an inkling that it might be related to done() (i.e. the completionHandler) being called too early and terminating the app before the task/operation can take place (see http://stackoverflow.com/a/29912511/1183749), though I have taken precautions to only call done() after completing my task (write to db). This, obviously, only works when the app is backgrounded and I don't know how else to test whether the completionHandler is being called at the right time and the app is not being terminated prematurely.

FYI: Background Modes for Remote Notifications is enabled in Capabilities.

Any ideas?

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.