Giter Site home page Giter Site logo

react-native-notifications's Introduction


React Native Notifications

npm Build Status npm (tag) npm (tag)

Handle all the aspects of push notifications for your app, including remote and local notifications, interactive notifications, silent notifications, and more.

All the native iOS notifications features are supported!

For information regarding proper integration with react-native-navigation, follow this wiki.

Requirements

Apps using React Native Notifications may target iOS 10 and Android 5.0 (API 21). You may use Windows, macOS or Linux as your development operating system.

iOS

  • Remote (push) notifications
  • Local notifications
  • Background/Managed notifications (notifications that can be cleared from the server, like Facebook messenger and Whatsapp web)
  • PushKit API (for VoIP and other background messages)
  • Interactive notifications (allows you to provide additional functionality to your users outside of your application such as action buttons)

Android

  • Receiving notifications in any App state (foreground, background, "dead")
  • Built-in notification drawer management
  • High degree of code extensibility to allow for advanced custom layouts and any specific notifications behavior as available by Android's API
  • Android equivalent of React-Native's implementation of PushNotificationsIOS.getInitialNotification().

Upcoming: local notifications, background-state Rx queue (iOS equivalent)

Quick Links

License

The MIT License.

See LICENSE

react-native-notifications's People

Contributors

adinin avatar artald avatar benjeau avatar bilal-abdeen avatar buttershub avatar d4vidi avatar danieleliraz avatar davidstoker avatar erkie avatar gperdomor avatar gran33 avatar guyca avatar henrikbjorn avatar igorgn avatar jastanton avatar lionerez1 avatar lucasgladding avatar mrousavy avatar msom avatar naturalclar avatar pennersr avatar radko93 avatar ravirajn22 avatar remarkablemark avatar rotemmiz avatar swabbass avatar weihangchen avatar wixmobile avatar yedidyak avatar yogevbd 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  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

react-native-notifications's Issues

Does not receive notification information on cold start (iOS)

Hi all,

I want to use the plugin only for local notifications. I can schedule notifications and receive them in the notificationcenter. When the application is in background or closed and I tap a notification in the notificationcenter it does as expected: the application goes to the foreground and executes the code in my notificationOpened eventListener callback.

However the callback argument only contains userInfo, when opened from background. If the app is opened from cold state I get no information about the notification I have open.

{"data": {}}

I first experienced the problem in my own project, running RN 41.2 and using RNNavigation. However I was able to replicate by installing your example app and firing a local notification.

let localNotification = NotificationsIOS.localNotification({ alertBody: "Received local notificiation!", alertTitle: "Local Notification Title", alertAction: "Click here to open", soundName: "chime.aiff", category: "SOME_CATEGORY", userInfo: {link: 'drug:adrenaline_1489999'}, fireDate: date.toISOString(), })

I have only tested on iOS

Trying to debug the problem in remote debugger I get:

RCTJSONStringify() encountered the following error: Invalid type in JSON write (UIConcreteLocalNotification)
Unhandled JS Exception: Cannot read property 'aps' of null

My guess is it probably related, but I do not know.

Android version

Hey guys, first of all thanks for your contribution, this is a brilliant peace of code and very usefull for RN comunity.
While iOS version looks complete, the lack of Android is very frustrating.
Do you have any plans to support Android and if so, when do you think it will be available for beta testing?

Unable to Retrieve Device Token

I'm not able to retrieve a device token with the following bit of code. The project renders as expected and it prompts the user for permission to use Push Notifications, but it's not logging a device token. Any thoughts on what is incorrect?

import NotificationsIOS from "react-native-notifications";
...
module.exports = class App extends Component {
...
constructor(props) {
	super(props);
	if (Platform.OS === "ios") {
		NotificationsIOS.addEventListener('remoteNotificationsRegistered', this.onPushRegistered.bind(this));
		NotificationsIOS.addEventListener('remoteNotificationsRegistrationFailed', this.onPushRegistrationFailed.bind(this));
		NotificationsIOS.requestPermissions();
	}
}

onPushRegistered(deviceToken) {
	console.log("Device Token Received", deviceToken);
}

onPushRegistrationFailed(error) {
	console.error(error);
}
...

Android Interactive Notifications

Hi! Thank you for this awesome project. We're currently using the iOS version and it works really great so far. I was just wondering if you'll also be adding Interactive Notifications feature for Android, and if so what an ETA might be? Can also help you guys beta test if needed.

Push Token is never sent to JS on Android.

I have been trying this since past 2 days. I have also tried debugging in library source code. But in the file GcmToken.java, sendTokenToJS() method is getting called. But "reactContext" is coming null. Following is my code.
` mReactRootView = new ReactRootView(this.getApplicationContext());
mReactInstanceManager = ReactInstanceManager.builder()
.setApplication(getApplication())
.setBundleAssetName("index.android.bundle")
.setJSMainModuleName("index.android")
.addPackage(new MainReactPackage())
.addPackage(new ReactAppCallbackModules())
.addPackage(new WebViewBridgePackage())
.addPackage(new ReactNativeContacts())
.addPackage(new AndroidKeyboardAdjustPackage(this))
.addPackage(new RNNotificationsPackage(getApplication()))
.setUseDeveloperSupport(BuildConfig.DEBUG)
.setInitialLifecycleState(LifecycleState.RESUMED)
.build();

mReactRootView.startReactApplication(mReactInstanceManager, "ReactApp", null);
**My Application Class has code**
private final ReactNativeHost mReactNativeHost = new ReactNativeHost(this) {
@OverRide
protected boolean getUseDeveloperSupport() {
return BuildConfig.DEBUG;
}

    @Override
    protected List<ReactPackage> getPackages() {
        return Arrays.<ReactPackage>asList(
                new MainReactPackage(),
                new RNNotificationsPackage(CoreApplication.this)
        );
    }
};

@Override
public ReactNativeHost getReactNativeHost() {
    return mReactNativeHost;
}

`
The only change in this is I am starting a React Application on specific Activity, that is my HomeActivity. Rest other activities such as Login, etc are written in Native Android.

Can someone please help?

Bad `removeEventListener` usage in README

I am sorry, I do not have the time to submit a PR, so I will leave this issue here instead.
The README says this:

import NotificationsIOS from 'react-native-notifications';

class App extends Component {
    constructor() {
        NotificationsIOS.addEventListener('remoteNotificationsRegistered', this.onPushRegistered.bind(this));
        NotificationsIOS.requestPermissions();
    }

    onPushRegistered(deviceToken) {
        console.log("Device Token Received", deviceToken);
    }

    componentWillUnmount() {
        // prevent memory leaks!
        NotificationsIOS.removeEventListener('remoteNotificationsRegistered', this.onPushRegistered.bind(this));
    }
}

But here the NotificationsIOS.removeEventListener wont' work since:

this.onPushRegistered.bind(this) !== this.onPushRegistered.bind(this)

[ios] RNNotifications.h not found

I manually linked everything: Imported library (xcodeproj), added the .a to Link Binary with Libraries, and added $(SRCROOT)/../node_modules/react-native-notifications/RNNotifications to header search paths for dev and release.

I am still getting
screen shot 2017-01-27 at 5 02 28 pm

when trying to import into appDelegate.m

Did I miss something?

I am using React Native 0.38.0 with RNN experimental.185. Full AppDelegate:
screen shot 2017-01-27 at 5 03 52 pm

null token??

Android... I've set everything up (I think). Project builds, seems happy. But the callback for .setRegistrationTokenUpdateListener gets called with a null. What's the story? Am I missing some configuration, or...?

AndroidManifest.xml:

<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.vie"
    android:versionCode="1"
    android:versionName="1.0">

    <uses-permission android:name="android.permission.INTERNET" />
    <uses-permission android:name="android.permission.SYSTEM_ALERT_WINDOW"/>
    <uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
    <uses-permission android:name="android.permission.WAKE_LOCK"/>

    <uses-sdk
        android:minSdkVersion="16"
        android:targetSdkVersion="22" />

    <application
      android:name=".MainApplication"
      android:allowBackup="true"
      android:label="@string/app_name"
      android:icon="@mipmap/ic_launcher"
      android:theme="@style/AppTheme">
      <meta-data android:name="com.wix.reactnativenotifications.gcmSenderId" android:value="590139615515\0"/>
      <meta-data android:name="com.facebook.sdk.ApplicationId" android:value="@string/facebook_app_id"/>
      <activity
        android:name=".MainActivity"
        android:label="@string/app_name"
        android:configChanges="keyboard|keyboardHidden|orientation|screenSize">
        <intent-filter>
            <action android:name="android.intent.action.MAIN" />
            <category android:name="android.intent.category.LAUNCHER" />
        </intent-filter>
      </activity>
      <activity android:name="com.facebook.react.devsupport.DevSettingsActivity" />
    </application>

</manifest>

Check Permissions

Hi! First off, I'm very appreciative for this package!
I'm using it on an iOS project for now, and on Android in the next couple of weeks.

I was wondering if there will be a checkPermissions method, or even something along the lines of permissionsDidChange...

Thanks!
Sam

Use UserNotifications.framework on iOS 10 and above

The currently used local and remote notification APIs are deprecated on iOS 10, but also, the new API allows more features, such as titles, subtitles and attachments in local and remote notifications, which were not possible using the old APIs. The framework should be updated with the UserNotifications.framework support.

Interactive notifications action not working

i am using Interactive notifications for some of my customs notification ,
but my app not launched on press of notification action normally in notification click app is launched but on interactive customs action its not working
here is my code ,
upvoteAction = new NotificationAction({
activationMode: "background",
title: "Start ",
identifier: "UPVOTE_ACTION"
}, (action, completed) => {
// here i am consuming notification data
this.onNotificationOpened(action.notification)
completed();
});

all action are fired that i can see in console but app is not launched , so what is issue

Android notifications won't wake up device

Hi,

First of all, I always successfully receive the push notifications that I'm sending from server side. However, they do not wake up the device if it's locked. There are also a couple more problems I've noticed that may be related to this.

I'm going to list all the instances of unusual behaviour of the notification system:

  1. If the device is locked (display off), the notifications are received, but they do not wake up the device, nor do they trigger any sound or vibration at all.
  2. If the device is unlocked and my app is completely closed or in background, my device receives the notifications but again, they do not trigger sound/vibration.
  3. If the device is unlocked and my app is opened/in foreground, the notifications are received, they do trigger the default sound and vibration, but their content is empty, as if I didn't specify a title or body.

The payload that I send to https://gcm-http.googleapis.com/gcm/send looks like this:

{  
    "notification": {  
        "title": "Notification title test",
        "body": "Notification description test"
     },
     "priority": "high",
     "collapse_key": "test",
     "sound": "default",
     "to":"fkvgOg..[...]..r7xbb"
}

I use [email protected] and [email protected].

If you have any idea about why this happens or if the issue is from somewhere else, please let me know. Thanks.

Enhance cancelLocalNotification API

In react-native cancelLocalNotification API, we can cancel a local notification based on the userInfo object that was provided when the notification was scheduled. So, I don't need to remember the notification ID for some event in order to cancel the notification.

In the current API in this package, I need to remember the notification ID for the notification of some event if I want to cancel it in future which is kind of a hassle. I can't even just have a map to map the event ID to notification ID because when the app is closed, the in-memory map will be flushed. So, I need to maintain this info in AsyncStorage. We can't also provide the notification ID when the notification is scheduled so that we can just have an algorithm to compute the notification ID for an event based on some properties of the event which will compute a same and unique notification ID for an event every time.

The use case is very common in reminders/alarms kind of apps where user schedules to be notified sometime in the future for some event but then changes the time of the event or cancel the event itself.

I think the API provided by react-native PushNotificationIOS to cancel local notification is very accommodating where we can just provide a userInfo object to cancel the notification and if there is any scheduled notification with the same userInfo object, it will be canceled. I think we should have something similar here too.

Understanding opening notifications when app is closed

My setup: on iOS I'm subscribing to foreground, background, and opened notifications and when my app boots I call consumeBackgroundQueue.

When I get a remote notification while the app is closed and I tap on the notification, the app boots. I am seeing opened notification as well as foreground notification. Is this expected?

When the app is the foreground I just get foreground
when the app is in the background I get background and when I tap I get opened,
but when the app is closed I would expect to get either just opened, or background and opened but I get foreground and opened. Quite odd.

Let me know, thanks!

Interactive Notifications action callback not fired on iOS

I'm using React 0.44 and the project was created from Expo XDE (https://expo.io) by using $ exp detach command.
Here my code:

// constructor
// Notification interaction
      let gotItAction = new NotificationAction({
        activationMode: "background", // foreground: open the app when user click action
        // title: String.fromCodePoint(0x1F44D),
        title: 'Got it!',
        identifier: "GOT_IT_ACTION"
      }, (action, completed) => {
        console.log("ACTION RECEIVED", action);
        // console.log(JSON.stringify(action));
        
        // You must call to completed(), otherwise the action will not be triggered
        completed();
      });
      
      let cancelBookingAction = new NotificationAction({
        activationMode: "background", // foreground: open the app when user click action
        title: "Cancel",
        identifier: "CANCEL_BOOKING_ACTION"
      }, (action, completed) => {
        console.log("ACTION RECEIVED", action);
        // console.log(JSON.stringify(action));
        
        completed();
      });
      
      let bookingCategory = new NotificationCategory({
        identifier: "BOOKING_CATEGORY",
        actions: [gotItAction, cancelBookingAction],
        context: "default"
      });
NotificationsIOS.requestPermissions([bookingCategory]);

// componentDidMount
NotificationsIOS.localNotification({
        fireDate: date.getTime(),
        alertBody: 'Your booking 1234',
        alertTitle: 'Hello 123',
        soundName: "chime.aiff",
        category: "BOOKING_CATEGORY",
        userInfo: {
          bookingId: 123
        }
      });

I can get the notification but when i try to click to Got it! and Cancel action, i dont see any logs in my console. What i'm expected is something like this: ACTION RECEIVED .... I dont know if i missing anything

I'm using manual link the project, the follow exactly the document in readme.
img_1363 png
img_1364 png
img_1365 jpg

Notification is blank on Android

I'm not sure what I'm doing wrong since others appear to be using this library for Android but my push messages are appearing "blank". I receive the push and I can see the push in the log with the message but the device just shows a blank push notification with the app icon and no text.

I switched to react-native-push-notification for Android and now my push notifications are appearing with text so something is going on with the wix push library. I haven't had time to dig into it and I'm not an Android expert so I'm not sure where to look. Hoping someone else can come to my rescue so I can use a single library for push.

What is the best way to use it with RNNavigation?

Hi, guys! Thanks for your libraries they are great. I have a question what is the best way to use RNNotifications with RNNavigation. In docs it says to subscribe to notifications in componentWillMount and remove listeners in componentWillUnmount of the root component e.g. App or something, but with RNNavigation we don't have one. We start App with startSingleScreenApp and that's it. Of course I can subscribe for notifications before call to startSingleScreenApp, but I won't be able to remove listeners. So what is a best practice to deal with it how should I use it with RNNavigation? Thanks in advance.

consumeBackgroundQueue not working (iOS 10.2)

I'm using this package along side wix/react-native-navigation, and I have my notification handlers set up in the root App class's constructor as follows:

// notice that this is just a simple class, it's not a React component
export default class App {
  constructor() {
    NotificationsIOS.addEventListener('remoteNotificationsRegistered', this.onPushRegistered.bind(this));
    NotificationsIOS.addEventListener('remoteNotificationsRegistrationFailed', this.onPushRegistrationFailed.bind(this));
    NotificationsIOS.addEventListener('notificationReceivedForeground', this.onNotificationReceivedForeground.bind(this));
    NotificationsIOS.addEventListener('notificationReceivedBackground', this.onNotificationReceivedBackground.bind(this));
    NotificationsIOS.addEventListener('notificationOpened', this.onNotificationOpened.bind(this));
    NotificationsIOS.requestPermissions();
    NotificationsIOS.consumeBackgroundQueue();

// ...rest of the code

However, when the app launches from a cold state after pressing a notification, there is never anything sent to the notification handlers. Any insight onto why this isn't working? Is it something to do with react-native-navigation?

Custom notifications on Android

Hello, are there any intentions to add support for fully custom notifications on Android?
That is, notifications with personalized XML layouts with any controls and any graphics.
Thanks.

installation - PushNotificationIOS needed?

Do we need to install PushNotificationIOS if we're using the react-native-notifications library. I'm presuming we don't need to because it's not mentioned in the installation guide?

__DEV__ is not defined

I get DEV is not defined when trying to build for iOS.
Here's the full exception:

> > ReferenceError: __DEV__ is not defined
> >     at Object.<anonymous> (/Users/oriharel/oriApp/NiyoRadar/node_modules/react-native/Libraries/react-native/react-native.js:15:5)
> >     at Module._compile (module.js:398:26)
> >     at Object.Module._extensions..js (module.js:405:10)
> >     at Module.load (module.js:344:32)
> >     at Function.Module._load (module.js:301:12)
> >     at Module.require (module.js:354:17)
> >     at require (internal/module.js:12:17)
> >     at /Users/oriharel/oriApp/NiyoRadar/node_modules/react-native/node_modules/babel-core/lib/transformation/file/options/option-manager.js:284:15
> >     at Array.map (native)
> > TransformError: /Users/oriharel/oriApp/NiyoRadar/node_modules/react-native-notifications/index.ios.js: __DEV__ is not defined
> transformed 802/803 (100%)[node-haste] Encountered an error while persisting cache:
> > ReferenceError: __DEV__ is not defined
> >     at Object.<anonymous> (/Users/oriharel/oriApp/NiyoRadar/node_modules/react-native/Libraries/react-native/react-native.js:15:5)
> >     at Module._compile (module.js:398:26)
> >     at Object.Module._extensions..js (module.js:405:10)
> >     at Module.load (module.js:344:32)
> >     at Function.Module._load (module.js:301:12)
> >     at Module.require (module.js:354:17)
> >     at require (internal/module.js:12:17)
> >     at /Users/oriharel/oriApp/NiyoRadar/node_modules/react-native/node_modules/babel-core/lib/transformation/file/options/option-manager.js:284:15
> >     at Array.map (native)
> > TransformError: /Users/oriharel/oriApp/NiyoRadar/node_modules/react-native-notifications/index.ios.js: __DEV__ is not defined

I use .babelrc file which has:

{
  'presets': ['react-native-stage-0'],
  'plugins': ['transform-decorators-legacy']
}

I need it because I use MobX and it has decorators.

[Update] - it also happens even without MobX.

consumeBackgroundQueue not always firing

Hi!

First of, great job with this package! πŸ˜„

I'm trying to use Interactive notifications to postpone tasks in my app. But when i press an action it does not always fire the Β΄consumeBackgroundQueueΒ΄ function. I'm calling it in the constructor of my app component, just like in the example:

constructor(props) {
    super(props);

    NotificationsIOS.addEventListener('remoteNotificationsRegistered', token => {
      Store.dispatch(updateUser({ pushToken: token }));
    });
    NotificationsIOS.addEventListener('notificationReceivedForeground', this.onLocalNotification.bind(this));
    NotificationsIOS.addEventListener('notificationReceivedBackground', () => console.log('background notification received'));
    NotificationsIOS.addEventListener('notificationOpened', this.onNotification.bind(this));

    NotificationsIOS.requestPermissions([cat]);
    NotificationsIOS.consumeBackgroundQueue();
  }

I have found a pattern. When i only press an action on a notification and the app is closed it's not firing but i i have multiple notification after each other and press on actions for 2-3 of them, it's firing.

Can i call the function some where else to get it to run every time?

display notification when application state is "dead"

Hi guys,

I'm moving from React Native Push Notification to this lib because RNPN doesn't work well with React-Native-Navigation...

I can receive notification if my application is in "dead" state. The icon is added to the system top bar and I got a vibration, that's all. How to display it with its content as the other apps do?

Here is an exemple of what we can do (without no code modification / addition) with RNPN.
screenshot_2016-12-27-15-26-09

Is it something we can do with Wix RN-Notifications? Or do we need to customize Notification Classes etc?

notificationReceivedBackground didn't fire

I have run the example, notificationReceivedForeground and notificationOpened work fine.But notificationReceivedBackground didn't fire, is there any possible reason cause this?

NotificationsAndroid.requestPermissions()

Hi! Is there a way to request permissions to the user to decline or accept notifications on Android? Because It seems that every time I open my app it's giving permissions without asking for them.

IOS: Remote notification only accepts "sandbox"

I'm having weird issue after I built my app for "release" in iOS. I have configured the certificates/pems on the server side but I can't figure out why it can only accept notifications from ssl://gateway.sandbox.push.apple.com:2195. I'm using PHP to send remote notification.

If it helps, I just recently switched to this package for additional features and it works great on dev. The previous package I used was the react-native-push-notification which accepts notification appropriately for both dev and production.

Am I missing something or this is a known issue? Thanks!

PS: I'm using RNN + redux

Android Simulator getInitialNotification returns undefined

When app is in foreground all works as expected, but then app is in background and it receives notification and user taps it app goes to foreground, but getInitialNotification returns undefined. I use android-gcm to send messages to the app.

Non Removable Notification

Hello people, very useful package, but I wonder if there is any way to make a non-removable notification with the current api.

Integration with ios + firebase?

Is it possible, and is there any documentation to use this library with ios and firebase?

I have been trying unsuccessfully to do this. When fetching the APNS token from firebase, I'm getting Failed to fetch APNS token Error Domain=com.firebase.iid Code=1001 "(null)". And a wrong token is passed to RNNotifications.

I am only able to get the correct token from firebase after it gets refreshed.

Here's a hacked implementation in my AppDelegate.m file:

/**
 * Copyright (c) 2015-present, Facebook, Inc.
 * All rights reserved.
 *
 * This source code is licensed under the BSD-style license found in the
 * LICENSE file in the root directory of this source tree. An additional grant
 * of patent rights can be found in the PATENTS file in the same directory.
 */

#import "AppDelegate.h"
#import "RCTBundleURLProvider.h"
#import "RCCManager.h"
#import "RCTRootView.h"
#import <FBSDKCoreKit/FBSDKCoreKit.h>
#import "Firebase.h"
#import "RNNotifications.h"

#if defined(__IPHONE_10_0) && __IPHONE_OS_VERSION_MAX_ALLOWED >= __IPHONE_10_0
@import UserNotifications;
#endif



@implementation AppDelegate

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
  NSURL *jsCodeLocation;
  
  jsCodeLocation = [[RCTBundleURLProvider sharedSettings] jsBundleURLForBundleRoot:@"index.ios" fallbackResource:nil];
  self.window = [[UIWindow alloc] initWithFrame:[UIScreen mainScreen].bounds];
  self.window.backgroundColor = [UIColor whiteColor];
  [[RCCManager sharedInstance] initBridgeWithBundleURL:jsCodeLocation];
  
  //  RCTRootView *rootView = [[RCTRootView alloc] initWithBundleURL:jsCodeLocation
  //                                                      moduleName:@"tbp"
  //                                            initialProperties:nil
  //                                                   launchOptions:launchOptions];
  //  rootView.backgroundColor = [[UIColor alloc] initWithRed:1.0f green:1.0f blue:1.0f alpha:1];
  //
  //  self.window = [[UIWindow alloc] initWithFrame:[UIScreen mainScreen].bounds];
  //  UIViewController *rootViewController = [UIViewController new];
  //  rootViewController.view = rootView;
  //  self.window.rootViewController = rootViewController;
  //  [self.window makeKeyAndVisible];
  
  [[UIApplication sharedApplication] registerForRemoteNotifications];

  // [START configure_firebase]
  [FIRApp configure];
  // [END configure_firebase]
  // [START add_token_refresh_observer]
  // Add observer for InstanceID token refresh callback.
  [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(tokenRefreshNotification:)
                                             name:kFIRInstanceIDTokenRefreshNotification object:nil];
  // [END add_token_refresh_observer]
  return [[FBSDKApplicationDelegate sharedInstance] application:application
                                didFinishLaunchingWithOptions:launchOptions];

  return YES;
}

// [START connect_to_fcm]
- (void)connectToFcm {
  // Won't connect since there is no token
  if (![[FIRInstanceID instanceID] token]) {
    return;
  }
  
  // Disconnect previous FCM connection if it exists.
  [[FIRMessaging messaging] disconnect];
  
  [[FIRMessaging messaging] connectWithCompletion:^(NSError * _Nullable error) {
    if (error != nil) {
      NSLog(@"Unable to connect to FCM. %@", error);
    } else {
      NSLog(@"Connected to FCM.");
    }
  }];
}
// [END connect_to_fcm]


// [START refresh_token]
- (void)tokenRefreshNotification:(NSNotification *)notification {
  // Note that this callback will be fired everytime a new token is generated, including the first
  // time. So if you need to retrieve the token as soon as it is available this is where that
  // should be done.
  NSString *refreshedToken = [[FIRInstanceID instanceID] token];
  NSLog(@"InstanceID token: %@", refreshedToken);
  
  // Connect to FCM since connection may have failed when attempted before having a token.
  [self connectToFcm];
  
  // TODO: If necessary send token to application server.
}
// [END refresh_token]



- (void)applicationDidBecomeActive:(UIApplication *)application {
  [self connectToFcm];
  [FBSDKAppEvents activateApp];
}


- (BOOL)application:(UIApplication *)application openURL:(NSURL *)url sourceApplication:(NSString *)sourceApplication annotation:(id)annotation {
  return [[FBSDKApplicationDelegate sharedInstance] application:application
                                                        openURL:url
                                              sourceApplication:sourceApplication
                                                     annotation:annotation];
}


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

- (void)application:(UIApplication *)application didRegisterForRemoteNotificationsWithDeviceToken:(NSData *)deviceToken {
  NSLog(@"APNs token retrieved: %@", deviceToken);
  
  // With swizzling disabled you must set the APNs token here.
  // [[FIRInstanceID instanceID] setAPNSToken:deviceToken type:FIRInstanceIDAPNSTokenTypeSandbox];
  [RNNotifications didRegisterForRemoteNotificationsWithDeviceToken:deviceToken];
}

- (void)application:(UIApplication *)application didFailToRegisterForRemoteNotificationsWithError:(NSError *)error {
  NSLog(@"Unable to register for remote notifications: %@", error);
  [RNNotifications didFailToRegisterForRemoteNotificationsWithError:error];
}

// Required for the notification event.
- (void)application:(UIApplication *)application didReceiveRemoteNotification:(NSDictionary *)notification {
  [RNNotifications didReceiveRemoteNotification:notification];
}


@end

XCode Nullability Errors

I have been getting errors when compiling for 0.40.0 and 0.41.0 due to the nullability requirements of Xcode.

By adding the nullable and nonnull types to the Dictionaries these errors can be fixed, as well as using a simple wrapper, though I would believe the type keywords to be the most future-proof solution.

https://developer.apple.com/swift/blog/?id=25

I will send a PR with the needed changes to save anyone the time and effort, or at least provide an example for another PR.

Android doesn't fire callbacks while in background

I noticed that on Android i get notifications but the app doesn't fire setNotificationReceivedListener
setNotificationOpenedListener callbacks if the app is in background. If you keep it on screen it works as expected. Any idea? I use RNN.

How to get the device ID in IOS

How to get device id in IOS , Any one let me know how to configuration to get device id
I've use

"dependencies": {
"native-base": "^0.5.2",
"react": "15.4.2",
"react-native": "0.42.0",
"react-native-loading-spinner-overlay": "^0.4.1",
"react-native-modal-datetime-picker": "^4.0.0",
"react-native-notifications": "^1.1.10",
"react-native-root-toast": "^1.0.3",
"react-native-router-flux": "3.38.0",
"react-native-vector-icons": "^4.0.0"
},

getInitialNotification()

Need an API for retrieving the initial notification from which app has been started.

This kind of API is required as PushNotificationIOS.getInitialNotification() only provides raw notification data.

As a side-note, this API should consider the fact that the app can be either started by swiping a local notification OR a remote one, and the handling should be different (remote notifs should be "wrapped" with the internal IOSNotification class).

Opening an Android application by notification tap

  • On cold start - PendingNotifications.getInitialNotification().then(...) returns undefined.
  • When app in background - the handler configured by NotificationsAndroid.setNotificationOpenedListener(...) is not called

App based on react-native-navigation and configured as described here.

"react-native": "0.44.0",
"react-native-navigation": "latest",
"react-native-notifications": "^1.1.10",

Any help?

Installation and Setup

When i open this page: linking-libraries-ios

I wonder to i need to really do the manually linking? or can use automatically?

Secondly, i dont know for sure why this library said open AppDelegate.m and import RNNotifications.h while there is only AppDelegate.swift when i open the Xcode project so i dont know what is the next step to do. I try to import RNNotifications but it seems that is not a right thing.

Please help

Handler issue.

I just started getting into react-native, so please bare with me. I walked through everything created a secondary component with just a view for the notifications on a test app. and got the error

handler is not a function.
here is the code.

/**
 * Sample React Native App
 * https://github.com/facebook/react-native
 * @flow
 */

import React, { Component } from 'react';
import {
  AppRegistry,
  StyleSheet,
  Text,
  View
} from 'react-native';

import NotificationsIOS from 'react-native-notifications';

class App extends Component {
    constructor(props) {
      super(props)
      var self = this
        NotificationsIOS.addEventListener('remoteNotificationsRegistered', self.onPushRegistered);
        NotificationsIOS.addEventListener('remoteNotificationsRegistrationFailed', self.onPushRegistrationFaled);
        NotificationsIOS.requestPermissions();
    }
    
    onPushRegistered(deviceToken) {
        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));
    }

    render(){return(<View />)}
}


export default class remoteNotify extends Component {
  
  render() {
    return (
      <View style={styles.container}>
        <Text style={styles.welcome}>
          Welcome to React Native!
        </Text>
        <Text style={styles.instructions}>
          To get started, edit index.ios.js
        </Text>
        <Text style={styles.instructions}>
          Press Cmd+R to reload,{'\n'}
          Cmd+D or shake for dev menu
        </Text>
        <App />
      </View>
    );
  }
}

const styles = StyleSheet.create({
  container: {
    flex: 1,
    justifyContent: 'center',
    alignItems: 'center',
    backgroundColor: '#F5FCFF',
  },
  welcome: {
    fontSize: 20,
    textAlign: 'center',
    margin: 10,
  },
  instructions: {
    textAlign: 'center',
    color: '#333333',
    marginBottom: 5,
  },
});

AppRegistry.registerComponent('remoteNotify', () => remoteNotify);

fetchCompletionHandler

Does this project support calling a fetchCompletionHandler after a remote push notification with content-available=1 set? Basically, I'm finding that if I don't call the completion handler after processing a push notification the OS penalises me and stops delivering notifications to me app.

-(void)application:(UIApplication *)application didReceiveRemoteNotification:(NSDictionary *)notification fetchCompletionHandler:(void (^)(UIBackgroundFetchResult))completionHandler {

... 

[RCTPushNotificationManager didReceiveRemoteNotification:notification];

// now what? how do we wait for the JS code to finish doing its stuff before calling...

completionHandler(UIBackgroundFetchResultNewData);

Issue while installing

I get following error when I try to install this in my project, What could be wrong?

β”œβ”€β”€ UNMET PEER DEPENDENCY [email protected]
β”œβ”€β”€ [email protected] extraneous
β”œβ”€β”€ [email protected] extraneous
β”œβ”€β”¬ [email protected]
β”‚ β”œβ”€β”€ [email protected]
β”‚ └── [email protected]
└── [email protected] extraneous

npm WARN [email protected] requires a peer of react@^15.3.2 but none was installed.
What could be wrong?

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.