Giter Site home page Giter Site logo

invertase / react-native-notifee Goto Github PK

View Code? Open in Web Editor NEW
467.0 16.0 31.0 41.98 MB

Moved to https://github.com/invertase/notifee

Home Page: https://invertase.io/blog/open-sourcing-notifee

License: Other

Java 10.43% JavaScript 2.31% TypeScript 72.90% Ruby 1.20% Objective-C 11.10% Shell 1.86% Starlark 0.20%
react-native android notifications ios fcm onesignal

react-native-notifee's Introduction

react-native-notifee's People

Contributors

cabljac avatar dackers86 avatar ehesp avatar helenaford avatar ismaelmiber avatar liamjones avatar mars-lan avatar mikehardy avatar nvojnovic avatar russellwheatley avatar saeedzhiany avatar salakar avatar umang-simform 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

react-native-notifee's Issues

Although user has cleared notificaitons, call to displayNotification() displays old notifications

After playing for the whole day with notiffe, I've noticed at the end of the day notifee.displayNotification() started to act a bit funky (hope it's not me sleep deprived :) ).

Although user has cleared all of the notifications, when new notification arrives and when I call notifee.displayNotification() to display new notification arrived, all of the old notifications will get displayed. This didn't happen when I started working with this package, so I assume it could be a bug? It also seems list of "old" notifications being displayed is getting longer and longer.

P.S.: Related to this, I've checked the package and docs to see if I could collapse these notifications with collapse_key, but I could find any mentions. I guess collapse keys are not supported at the moment? https://firebase.google.com/docs/cloud-messaging/http-server-ref#downstream-http-messages-plain-text

getInitialNotification doesn't work

Hi guys! Now I'm testing your package in debug mode. For my product is very critical how 'App open events' feature works. Before buying the package I have to be sure that this feature is fully workable. But in some case I can't test it. I call this part on 'componentDidMount'

 const initialNotification = await notifee.getInitialNotification();
        if (initialNotification) {
            console.log('Notification caused application to open', initialNotification.notification);
            console.log('Press action used to open the app', initialNotification.pressAction);
        }

I always get null in Android. Then I dig into native code and found following:

    @KeepForSdk
    public void getInitialNotification(MethodCallResult<Bundle> var1) {
        if (nz_f.nz_t()) {
            nz_f.nz_t("getInitialNotification");
            var1.onComplete((Exception)null, (Object)null);
        } else {
            nZ_ne var2;
            if ((var2 = (nZ_ne)nz_t.nZ_o.nz_n.removeStickyEvent(nZ_ne.class)) == null) {
                var1.onComplete((Exception)null, (Object)null);
            } else {
                MethodCallResult var10000 = var1;
                Bundle var3;
                Bundle var10001 = var3 = new Bundle;
                var3.<init>();
                var3.putAll(var2.nZ_o);
                var10001.putBundle("notification", var2.nz_n.toBundle());
                var10000.onComplete((Exception)null, var3);
            }
        }

    }

I moved to nz_t method and get this :

 public static boolean nz_t() {
        if ((n.o.t.i.f.e.e.nZ_o.nz_n.getApplicationInfo().flags & 2) != 0) {
            return false;
        } else {
            int var0 = nz_nn.nZ_o.nz_n("lvs", 1);
            int var1;
            return (var1 = nz_nn.nZ_o.nz_n("rvs", 1)) != 1 && var1 != 0 || var0 != 1 && var0 != 0;
        }
    }

It looks like method always return null if app is run in debug mode.
Of cause I can be wrong so please tell how can I test "app open event feature" in debug mode.

[Android] - cannot create channel

I'm not able to create a notification channel with the v. 0.3.0 nor current master.

Steps to reproduce:

import notifee, { Importance } from '@notifee/react-native'

 notifee.createChannel({
   id: 'default',
   name: 'Default channel',
   importance: Importance.DEFAULT
})

Error:
notifee.createChannel(*) Cannot read property DEFAULT of undefined. Changing importance to number eg. 4 causes same error.

EDIT:
Changing import from '..' to '../types/Notification' fixes the issue.
https://github.com/notifee/react-native-notifee/blob/master/src/validators/validateAndroidChannel.ts#L11

Not sure why TS can't resolve it I have typescript in version 3.8.3

Push Notification sent through firebase do not trigger in foreground in Android release build

Hi, This code is working fine when tested on debug build. But on the release build local push notification generated by notifee not working.

Here is my package.json :
"@notifee/react-native": "^0.4.0",
"@react-native-firebase/analytics": "6.4.1-alpha.0",
"@react-native-firebase/app": "6.4.1-alpha.0",
"@react-native-firebase/auth": "6.4.1-alpha.0",
"@react-native-firebase/crashlytics": "6.4.1-alpha.0",
"@react-native-firebase/dynamic-links": "6.4.1-alpha.0",
"@react-native-firebase/iid": "6.4.1-alpha.0",
"@react-native-firebase/messaging": "6.4.1-alpha.0",

Code used to trigger local notification:

async unsubscribe() {
firebase.messaging().onMessage(async remoteMessage => {
try {
const channelId = await notifee.createChannel({
id: "default",
name: "Default Channel"
});
// Display a notification
await notifee.displayNotification({
title: remoteMessage.notification.title,
body: remoteMessage.notification.body,
ios: {
importance: Importance.HIGH
},
android: {
channelId
}
});
} catch (e) {
console.log(e);
}
});

Firebase-related?

Is this module related to r-n-Firebase or not?
Can I, for instance, register to fireabase nototification topics without it ?

Execution failed for task ':notifee_react-native:bundleReleaseAar'.

Hi,

I've just purchased a license for Notifee and have been integrating within my app. So far so good, the documentation is clear enough to get going and I've got the integration with Firebase/FCM working for the Android emulator so thanks for the hard work so far!

However I'm having trouble assembling for testing on a physical device: ./gradlew assembleRelease with the exception error

Execution failed for task ':notifee_react-native:bundleReleaseAar'.
> Direct local .aar file dependencies are not supported when building an AAR. The resulting AAR would be broken because the classes and Android resources from any local .aar file dependencies would not be packaged in the resulting AAR. Previous versions of the Android Gradle Plugin produce broken AARs in this case too (despite not throwing this error). The following direct local .aar file dependencies of the :notifee_react-native project caused this error: ***/node_modules/@notifee/react-native/android/libs/notifee_core_release.aar

I'm assuming that this is to do with my upgrade of gradle version

------------------------------------------------------------
Gradle 6.1.1
------------------------------------------------------------

Build time:   2020-01-24 22:30:24 UTC
Revision:     a8c3750babb99d1894378073499d6716a1a1fa5d

Kotlin:       1.3.61
Groovy:       2.5.8
Ant:          Apache Ant(TM) version 1.10.7 compiled on September 1 2019
JVM:          1.8.0_242 (AdoptOpenJDK 25.242-b08)
OS:           Mac OS X 10.15.4 x86_64

As the only reference I've found elsewhere to this issue is here

I'm not very familiar with gradle management but I'm assuming directly referencing the .aar file probably only a temporary fix?

largeIcon not working + small icon?

Hello,

I can't get the largeIcon to work with my image.
I'm also wondering if functionality has been built yet to change the icon from a square to a custom one? Is this the smallIcon for which documentation is in progress? Edit: figured this out

Please see my setup and a screenshot below.

Here is my code:
I've set up a hook that gets called in the main App.js, to set up the push notifications.
(*note the strange conditional import, this is so that I can keep building our ios app - if there is a better way please let me know!)
I'm sending push notifications from the server using firebase-admin (nodejs).

react_native/src/hooks/usePushNotifications.js:

import { useState, useEffect } from 'react';
import messaging from '@react-native-firebase/messaging';
let notifee;
if (Platform.OS === 'android') { // 👈 * never done this before, if there's a better way, please share!
  notifee = require('@notifee/react-native').default;
}

export default function usePushNotifications() {
  const [pushNotificationsReady, setPushNotificationsReady] = useState(false);

  useEffect(() => {
    if (Platform.OS === 'android') {
      setupPushNotificationHandlers().then(() => setPushNotificationsReady(true));
    } else {
      setPushNotificationsReady(true);
    }
  }, []);

  async function setupPushNotificationHandlers() {
    messaging().onMessage(onMessageReceived);
    messaging().setBackgroundMessageHandler(onMessageReceived);
  }

  async function onMessageReceived(message) {
    const channelId = await notifee.createChannel({
      id: 'default',
      name: 'Default Channel',
    });
    console.log('---@channelId --- usePushNotifications.js: onMessageReceived, L30');
    console.log(channelId);
    const notification = JSON.parse(message.data.notifee);
    // notification.android.largeIcon = require('../assets/images/img_name_196px.jpg'); // 👈 this throws an error: 'notification.android.largeIcon' expected a string value.
    // notification.android.largeIcon = 'https://i.pinimg.com/originals/42/81/53/428153d3084285c6292dd84e441ae97d.png' // 👈  this works
    notification.android.largeIcon = 'ic_launcher_custom'; // 👈 this only works sometimes, more info below**
    console.log('---@notification --- usePushNotifications.js: onMessageReceived, L36');
    console.log(notification);
    notifee.displayNotification(notification);
  }

  return {
    pushNotificationsReady,
  };
}

And this is my notifications object that is being logged right before

notifee.displayNotification(notification)
---@notification --- usePushNotifications.js: onMessageReceived, L36
{
  title: "Test",
  body: "You did it!",
  android: {
    color: "#c40018",
    channelId: "default",
    largeIcon: "ic_launcher_custom"
  },
  subtitle: "&#129395;"
}

image

** I've tried a few mipmaps and it seems like they only work if the mipmap does not have a .xml in the folder. If there is an .xml file in the folder of the mipmap I want to use, it will not work.

Thanks!

onForegroundEvent not fired

Android
debug
onForegroundEvent not fired

      notifee.onForegroundEvent((type,detail)=>{
        alert('a')
        console.log('Nothing happen');
        console.log(type);
        console.log(detail)

      })

Alternative

Does anyone know about a alternative for this library?

Unable to build library as standalone project

I wanted to open this library as a standalone project in IDE, so I tried to build the project on my PC, but I noticed some errors,

  • genversion is not listed in devDependencies section to install automatically by yarn install or npm install.
  • after installing it manually and run npm install I got this error that seems related to tsconfig file in the build phase.
> @notifee/[email protected] prepare C:\Users\USER\Desktop\react-native-notifee
> npm run build


> @notifee/[email protected] build C:\Users\USER\Desktop\react-native-notifee
> genversion --es6 --semi src/version.ts && tsc

tsconfig.json:12:5 - error TS5053: Option 'allowJs' cannot be specified with option 'declaration'.

12     "allowJs": true
       ~~~~~~~~~


tsconfig.json:17:6 - error TS5053: Option 'allowJs' cannot be specified with option 'declaration'.

17      "declaration": true,                   /* Generates corresponding '.d.ts' file. */
        ~~~~~~~~~~~~~


tsconfig.json:17:6 - error TS5053: Option 'declaration' cannot be specified with option 'isolatedModules'.

17      "declaration": true,                   /* Generates corresponding '.d.ts' file. */
        ~~~~~~~~~~~~~


tsconfig.json:26:5 - error TS5053: Option 'declaration' cannot be specified with option 'isolatedModules'.

26     "isolatedModules": true

install error

When I write "pod install".
I just get the following error.

[!] CocoaPods could not find compatible versions for pod "RNNotifee":
In Podfile:
RNNotifee (from ../node_modules/@notifee/react-native)

Specs satisfying the RNNotifee (from ../node_modules/@notifee/react-native) dependency were found, but they required a higher minimum deployment target.

Add information how to support notifee when more than one push provider is used

Android doesn't allow an app to have more than one handler for com.google.firebase.MESSAGING_EVENT intent filter action. Only the first registered service will handle a firebase message. If you need to use multiple push providers, you have to make custom handler / register your custom FirebaseMessagingService service, eg.

public class PushProvidersHandler extends FirebaseMessagingService {
    @Override
    public void onNewToken(String token) {
        super.onNewToken(token);
        // Do something with providers here
        ....
    }

    @Override
    public void onMessageReceived(RemoteMessage remoteMessage) {
        super.onMessageReceived(remoteMessage);
        // Do something with providers here
        ....
    }
}

[Android, MIUI] Notifications will be displayed as silent

Prerequisites:
Latest versions packages
MIUI Global 11.0.3 (Android 10)

Steps to reproduce:

index.js

// Register background handler
messaging().setBackgroundMessageHandler(async remoteMessage => {
    // Create a channel 
    const channelId = await notifee.createChannel({
        id: 'PIKS',
        name: 'PIKS',
        lights: true,
        vibration: true,
        importance: 4,
        visibility: 1
    });
    // Display a notification
    await notifee.displayNotification({
        title: 'Notification Title',
        body: 'Main body content of the notification',
        android: {
            channelId,
            importance: 4,
            visibility: 1
        },
    });

    console.log('Message handled in the background!', JSON.stringify(remoteMessage));
})

Server

var message = {
    token: tokenSnapshot,
    notification: {
        title: "Title",
        body: "Body",
    },
    android: {
        priority: 'high',
        notification: {
            sound: 'default',
            priority: 'high',
            visibility: 'public',
            channelId: 'PIKS'
        },
    },
};

Result:

  • notification is silent
  • no vibration
  • no sound
  • nothing appears on the lock screen

In the attached picture Channel is created in this way

Screenshot_2020-04-14-12-51-45-501_com android settings

The notification is only visible when the user checks if there is any new notification

Expected result:

  • vibration
  • sound
  • notification on lock screen

ScheduleNotification ? [question]

Hi !

A quick question about scheduled notifications: in the doc there is an empty section about it. Does it mean it's not implemented yet, or does it means it's there but documentation about it is still under progress ?

Thanks !

Push Notification sent through firebase do not trigger foreground or background events.

Using @react-native-firebase/app (6.3.4) and @react-native-firebase/messaging (6.3.4) for data messages yet notification and data messages both trigger the messaging onMessage function and notifee background or foreground events do not get triggered.

init Background code

const initBackground = async () => {
	notifee.onBackgroundEvent(async ({type, detail}) => {
		const {notification, pressAction} = detail;
	switch (type) {
		case EventType.PRESS:
			console.log("Notification Pressed when app in background", notification);
			await notifee.cancelNotification(notification.id);
			break;

		case EventType.ACTION_PRESS:
			console.log("User Pressed Action on Notification", detail);
			break;

		case EventType.DELIVERED:
			console.log("Notification Delivered", notification);
			break;

		case EventType.DISMISSED:
			console.log("User Dismissed the Notification", notification);
			break;

		default:
			console.log("Not sure what to do with this info", {type, detail});
			break;
	}
})

};

init Foreground code

function initForeground() {
	useEffect(() => {
		return notifee.onForegroundEvent(({type, detail}) => {
			switch (type) {
				case EventType.DISMISSED:
					console.log('User dismissed notification', detail.notification);
					break;
				case EventType.PRESS:
					console.log('User pressed notification', detail.notification);
					break;
				case EventType.DELIVERED:
					console.log("User Notification Delivered: ", detail);
					break;
			}
		});
	}, []);
}

These do get called if a notification was created and displayed using notifee but not for Push Notification.

Which features do react-native-notifee have that react-native-firebase/messaging v7 doesn't?

Sorry if this is the wrong place, but I am very confused about the versions of react-native-firebase/react-native-notifee which works or not with push notifications.
On this thread it says that v6 does not support firebase notifications, but now on v7 it has docs and have this feature back again. On the other side you have created a new paid lib (react-native-notifee) that apparently does the exact same thing that react-native-firebase v7 does at this moment, with some lack of some features (does not allow to integrate with any 3rd party messaging services), so my questions ares:

  • What are the differences between the lib react-native-firebase v5, v7 and react-native-notifee?

  • Can I still use the react-native-firebase v7 on production to receive push notification on both Android/iOS platform?

  • Can I migrate react-native-firebase v7 to react-native-notifee on the future when it leaves the alpha phase?

Build Issue: Cannot find symbol .cancelAllNotifictions (mistyped?)

I've created my project off of @react-native-firebase/template and I've installed notifee with yarn add @notifee/react-native (running this on Windows, Node v12.14.1, react-native v0.61.5).

When I run react-native run-android the build fails with exception:

Execution failed for task ':@notifee_react-native:compileDebugJavaWithJavac'.

....

...\node_modules\@notifee\react-native\android\src\main\java\io\invertase\notifee\NotifeeApiModule.java:45: error: cannot find symbol
      .cancelAllNotifictions((e, aVoid) -> NotifeeReactUtils.promiseResolver(promise, e));
      ^
  symbol:   method cancelAllNotifictions((e,aVoid)-[...]e, e))
  location: class Notifee

It seems like there is a typo in cancelAllNotifictions, should be cancelAllNotificAtions.

Incorrect iOS APNS Token

I am trying to implement this package (I purchased a license) along with react-native-firebase. After following all the steps in the documentation, I can receive notifications on Android and iOS using the Google FCM console. I can also get the device token for Android devices and receive sent notifications using AWS SNS.

I am having a problem with iOS and AWS SNS however. It appears that the token I am getting when I call messaging().getAPNSToken() is NOT correct.

I set the FirebaseAppDelegateProxyEnabled option to NO in my Info.plist file also, but the token appears to be incorrect.

When I register the token I get from my iOS device in SNS as an endpoint and publish a message to it, AWS disables it and generates the following failure message:

"EventType":"DeliveryFailure","FailureMessage":"Platform token associated with the endpoint is not valid","FailureType":"InvalidPlatformToken"

I am trying the following code:

messaging()
        .getToken()
        .then(token => {
          console.log('TOKEN: ', token); //gives me the FCM token...not good for iOS AWS SNS
        });

messaging()
            .getAPNSToken()
            .then(token => {
              console.log('iOS TOKEN: ', token.toLowerCase()); //if I dont make the token lowercase, I cannot register it as an endpoint in AWS. 
//Also this token is different than the FCM token but AWS SNS says it's not valid
            });

So the TLDR is, how can I get the correct iOS device token that will work with AWS SNS?

Also is the fact that the getAPNSToken needs to be converted to lowercase should be documented, took me quite a while to figure that out.

Thanks.

iOS 12 physical device (iPhone 6)
react native: 0.61.5
notifee: 0.5.1
react native fcm: 7.1.0

Pricing

I'm not sure if this is the right place to ask about the pricing, if it's not, feel free to remove this issue.

As a software developer, I completely understand how much effort it requires to develop a library like this, and I fully support you charging for it.

That being said, I feel that the price is too expensive for indie developers and too cheap for enterprises. What are your thoughts on this?

Are you considering maybe a lite version, or a separate pricing for indie developers? I would really love to use Notifee if the price comes down to somewhere below $50.

Again, please don't take this as a criticism or an effort to undervalue all the work that went into this library, I am only asking out of curiosity.

Foreground notification not working in android build release

Hi, I'm facing issue of failed to display foreground notification in android build release, background is working.Now I'm using notifee.displayNotification to display notification received.
Hope someone can help me, because I have been stuck in this problem many days

"@react-native-firebase/app": "^6.4.0",
"@react-native-firebase/crashlytics": "^6.4.0",
"@react-native-firebase/messaging": "^6.4.0",

notifee.displayNotification({
title: title,
body: body,
android: {
channelId: 'Default',
asForegroundService: true,
style: { type: AndroidStyle.BIGPICTURE, picture: android.imageUrl},
},
})

[Android] Notifications stop being received after 90sec in background

Hi! Notification in foreground works great, but I'm having issues in background:

Versions:
react: 16.9.0
react-native: 0.61.5
@notifee/react-native: 0.4.0
@react-native-firebase/app: 6.4.1-alpha.0
@react-native-firebase/messaging: 6.4.1-alpha.0
Nodejs Backend: firebase-admin: 8.10.0

Issue 1: I can't receive any background message, if I don't receive at least one foreground message first.

Issue 2: When I put the application in background state or close it(by swiping it away from applications list), notifications stop being received after 90 seconds (I tried sending a notification every 10 sec). It looks like some kind of sleep mode or timeout... The only ways to wake the reception up(just for 90 other seconds) without re-opening the app are :

  • Sending a test notification via the Firebase console.
  • Swiping a previously received notification (which triggers notifee.onBackgroundEvent).

index.js

/**
 * @format
 */
import {AppRegistry} from 'react-native';
import App from './App';
import {name as appName} from './app.json';
import messaging from '@react-native-firebase/messaging';
import notifee, { Importance } from '@notifee/react-native';

const onMessageReceived = async (message) => {
  console.log("onMessageReceived(), message=", message);
  notifee.displayNotification(JSON.parse(message.data.notifee));
}

messaging().registerDeviceForRemoteMessages();
messaging().onMessage(onMessageReceived);
messaging().setBackgroundMessageHandler(onMessageReceived);

notifee.createChannel({
  id: 'chatMessages',
  name: 'Chat messages',
  importance: Importance.HIGH,
});

notifee.onBackgroundEvent(async ({ type, detail }) => {
  const { notification, pressAction } = detail;
  console.log("onBackgroundEvent(), notification=", notification);
  // not handled for now...
});

AppRegistry.registerComponent(appName, () => App);

Payload from backend:

const message = {
   tokens,
   data: {
      notifee: JSON.stringify({
         title: 'Title',
         body: 'Body',
         android: {
            channelId: 'chatMessages',
         },
      }),
   },
}

Also, on my backend, I send the notification with _firebaseAdmin.messaging().sendMulticast(message), which considers the message as successfuly sent, even when not received due to this background mode issues.

Thanks,
Romain

EDIT: now I also tested on an emulator, same behavior.

Using summaryArguments in iOS displayNotification causes notifications not to appear

Whenever I use summaryArgument and summaryArgumentCount (I have not attempted with just one defined but since summaryArgumentCount defaults whereas summaryArgument does not, I assume summaryArgument is the issue.), displayNotification does not show any notifications in neither background nor foreground.

For a reference of my code, I followed the FCM intergration guide to a T, meaning both onMessage and setBackgroundMessageHandler both direct to a function listed as onMessageReceived that goes through message types and displays notifications based on the types as well as different variables. This code is located in my index.js file.

Some direct reference of my code below is an example of the issue iOS category and the code that had the problem directly. As far as I know, nothing outside of what I listed interacts with the segment of execution.

   await notifee.setNotificationCategories([
    {
      id: 'newConversation',
    },
    {
      id: 'message',
      summaryFormat: 'You have %u+ unread messages from %@.',
      actions: [{
        id: 'reply',
        title: 'Reply',
        input: true,
      }]
    }
        notifee.displayNotification({
          title: message.data.userName,
          body: message.data.messageText,
          data: message.data,
          android: {
            channelId: 'message',
            timestamp: Date.now(),
            showTimestamp: true,
            largeIcon: message.data.avatar ? message.data.avatar : '' // I use a direct link here as placeholder because local image throws an error, I omitted the link. I created a separate issue for this
          },
          ios: {
            categoryId: 'message',
            importance: Importance.DEFAULT,
            summaryArgument: message.data.userName,
            summaryArgumentCount: 3
          }
        })

With summaryArgument and summaryArgumentCount commented out, the notifications display properly in both background and foreground. It's only when I bring them in that they do not work.

Exception thrown when notification is clicked but the app is closed (running in background)

There aren't many details about what went wrong, so I'm not sure if is it Notifee or my code.

image

And bellow is my code (notification is never sent to notifeeBootstrap after I click it with app closed or in background).

import React, {useEffect, useState} from 'react';
import Navigation from './src/Navigation';
import * as NavigationService from './src/services/navigation';
import {AppearanceProvider, useColorScheme} from 'react-native-appearance';
import {isPreferredThemeDark} from './src/services/theme';
import {messaging} from './src/services/firebase';
import notifee from '@notifee/react-native';
import * as NotifeeService from './src/services/notifications';
import {BusyIndicator} from './src/screens/BusyIndicator';

export default function App() {
  const userPreferredTheme = useColorScheme();
  const [loadingNotification, setLoadingNotification] = useState(true);

  useEffect(() => {
    NotifeeService.notifeeBootstrap().then(() => setLoadingNotification(false)).catch(console.error);

    messaging.setBackgroundMessageHandler(NotifeeService.onMessageReceived); //when app is closed and notification is received
    messaging.onMessage(NotifeeService.onMessageReceived); //when app is open and notification is received

    return notifee.onEvent(NotifeeService.notifeeEventHandler);
  }, []);

  if (loadingNotification) {
    return <BusyIndicator/>;
  }

  return <AppearanceProvider>
    <Navigation
      ref={NavigationService.init}
      theme={isPreferredThemeDark(userPreferredTheme) ? 'dark' : 'light'}
    />
  </AppearanceProvider>;
}

[iOS] - IOSNotificationSettings is missing provisional permission

As a developer, I can't detect that user selected provisional permission.
This permission is requestable with requestPermission method, but IOSNotificationSettings returned with promise misses provisional flag.

Use case:
On app launch, I would like to request provisional permission silently and ask the user for full permissions after some time. With the current implementation, I'm not able to say if the user has provisional permission or not. I was trying to overcome it with alert or authorizationStatus flags but they won't work if I manually block permissions and grant it later.

[iOS] - createCategory is not a function

Prerequisites:

@notifee/react-native: 0.4.0
iPhone simulator

Steps to reproduce:

import notifee from '@notifee/react-native'

notifee.createCategory({
    id: 'test'
})

Result:

Unhandled JS Exception: TypeError: this.native.createCategory is not a function. (In 'this.native.createCategory(options)', 'this.native.createCategory' is undefined)

[iOS/Android] Missing functionalities

We are using notifee in our production app and even being in alpha it is serving its purpose very well.
As we all know there are many things still pending but I think right now it misses 2 basic yet important features.

  1. cancelAllNotifications function is not working on iOS (we want to clear all notifications when app is opened)
  2. Not able to get the current badge count (we want to perform some activity when user have badge count while launching the app)
  3. Ability to set badge count (It was supported in RNFirebase) but in the current version of notifee we are not able to set badge.

We are using 0.4.0 and I can say we are able to receive/display a notification in android/iOS perfectly for foreground as well as background.
We are looking forward to hearing from the dev team as according to us these are core features that will be required by most of the apps.

Feature request: do not use notifee.config.json and initialize lib manually

I have multiple environments: production, staging. That means I have to have several notifee.config.json files with primary and secondary keys and copy the right one during the build.

I would prefer that there would be a way to initialize the library in this way: Notifee.initializeLibrary(key) from JS code.

[iOS] - displayNotification not working

Prerequisites:

@notifee/react-native: 0.3.0
@react-native-firebase/messaging: 6.4.0-rc4
iOS (physical device)

Steps to reproduce:

import messaging from '@react-native-firebase/messaging'
import notifee, { Importance } from '@notifee/react-native'

useEffect(() => {
    const unsubscribe = messaging()
        .onMessage(message => {
             console.log('received on foreground')
             
             notifee.displayNotification({
                  title: 'Title',
                  body: 'Message',
                  ios: {
                       importance: Importance.HIGH
                  }
             })
             .then(console.log)
             .catch(error => console.log('Error', error)
        })

    return () => unsubscribe()
}, [])

Result:

received on foreground
9PRew2UGTykhPkxZhd1E (from then's console.log)

Expected result:

received on foreground
Message has been displayed on iOS
9PRew2UGTykhPkxZhd1E (from then's console.log)

Build issue on fresh project

I am getting an issue installing notifee in my new react-native project. Only notifee has been added with the default typescript template.

    "@notifee/react-native": "0.1.0",
    "react": "16.9.0",
    "react-native": "0.61.5"

The error seems similar to #3

> Task :@notifee_react-native:compileDebugJavaWithJavac FAILED

Deprecated Gradle features were used in this build, making it incompatible with Gradle 6.0.
Use '--warning-mode all' to show the individual deprecation warnings.
See https://docs.gradle.org/5.5/userguide/command_line_interface.html#sec:command_line_warnings
9 actionable tasks: 1 executed, 8 up-to-date
/home/jomik/projects/fitnessapp/node_modules/@notifee/react-native/android/src/main/java/io/invertase/notifee/NotifeeAp
iModule.java:38: error: cannot find symbol
      (e, aVoid) -> NotifeeReactUtils.promiseResolver(promise, e)
      ^
  symbol:   method metafactory(Lookup,String,MethodType,MethodType,MethodHandle,MethodType)
  location: interface LambdaMetafactory
Fatal Error: Unable to find method metafactory

FAILURE: Build failed with an exception.

* What went wrong:
Execution failed for task ':@notifee_react-native:compileDebugJavaWithJavac'.

Chronometer event

Hi,
I'm try to make a notification with a countdown, for that I used the follow configuration:
{
timestamp: Date.now() + 300000 ,
showChronometer: true,
chronometerDirection: 'down'
}
the chronometer, works well, but I don't have any event to make possible close the notification, or stop chronometer when the chronometre reaches 0. and if i try use a setTimeout doesn't work in background

do you have any solution or idea to solve that?

thanks

Foreground iOS not working

Hi, I'm facing issue of failed to display foreground notification in iOS , background is working.Now I'm using react-native-push-notification to display notification received.
Hope someone can help me, because I have been stuck in this problem many days.

PushNotification.localNotification({
  title: title,
  message: body,
  bigText: body,
})

"@react-native-firebase/app": "^6.4.0",
"@react-native-firebase/messaging": "^6.4.0",

onBackgroundEvent do not trigger when app have been kill.

Platform:
Android simulator (not sure on iOS)

Situation:

  1. Receive the notification on foreground.
  2. Swipe the app and then click the notification
  3. The result is just reboot the app, it doesn't trigger notifee.onBackgroundEvent()

Version:
"react-native": "0.60.5",
"@react-native-firebase/messaging": "^6.7.1",
"@notifee/react-native": "^0.4.0",

A function to handle display notification on foreground.

export const getMessageInForeground = () => {
  return dispatch => {

    messaging().onMessage(async remoteMessage => {
      // Display a notification
      const { notification, data } = remoteMessage;
      const title = notification.title;
      const body = notification.body;

      // Create a channel , set id and name to important , show foreground dialog
      const channelId = await notifee.createChannel({
        id: 'important',
        name: 'Important Notifications',
        importance: Importance.HIGH,
        badge: true,
      });
      
      await notifee.displayNotification({
        title: title,
        body: body,
        data,
        android: {
          channelId,
          pressAction: {
            launchActivity: "default",
            id: "default",
          },
        },
        importance: Importance.HIGH,
        badgeIconType: AndroidBadgeIconType.SMALL,
        ios: {
          importance: Importance.HIGH,
        },
      });
    });
    
    // Handle the notification when app on foreground
    notifee.onForegroundEvent(({ type, detail }) => {
      const { notification } = detail;

      switch (type) {
        case EventType.DISMISSED:
          console.log('User dismissed notification', detail.notification);
          break;
        case EventType.PRESS:
          // handle the notification and do something
          break;
      }
    });
    // APP receive notification on foreground, if go to background and click the notification
    notifee.onBackgroundEvent(async ({ type, detail }) => {
      const { notification, pressAction } = detail;

      switch (type) {
        case EventType.PRESS:
          // handle the notification and do something
          break;
      }
      // Check if the user pressed the "Mark as read" action
      if (type === EventType.ACTION_PRESS && pressAction.id === 'mark-as-read') {
        // Update external API
        // Remove the notification
        await notifee.cancelNotification(notification.id);
      }
    });

  };
};

AndroidManifest.xml

<manifest xmlns:android="http://schemas.android.com/apk/res/android"
  xmlns:tools="http://schemas.android.com/tools"
  package="com.test.test222">

    <uses-permission android:name="android.permission.INTERNET" />
    <uses-permission android:name="android.permission.WAKE_LOCK" />
    <uses-permission android:name="android.permission.CAMERA" />
    <uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED" />
    <uses-permission android:name="android.permission.VIBRATE" />
    <uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
    <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
    <!--For device brightness-->
    <uses-permission android:name="android.permission.WRITE_SETTINGS"
        tools:ignore="ProtectedPermissions" />

    <application
      android:name="com.test.test222.MainApplication"
      android:label="@string/app_name"
      android:icon="@mipmap/ic_launcher"
      android:roundIcon="@mipmap/ic_launcher"
      android:usesCleartextTraffic="true"
      android:allowBackup="false"
      android:theme="@style/AppTheme">

      <activity
        android:name="com.test.test222.MainActivity"
        android:label="@string/app_name"
        android:screenOrientation="portrait"
        android:configChanges="keyboard|keyboardHidden|orientation|screenSize"
        android:windowSoftInputMode="adjustResize"
        android:launchMode="singleTop">
        <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>

Release Status

With all this noise in the previous thread the main question still stays without an answer:

Are there any news about the release date /alpha, beta, pre/ ?

fresh Android build failure

Hi Team,

I'm trying to take notifee for a ride, but am getting this error on a fresh install

FAILURE: Build failed with an exception.

* What went wrong:
Execution failed for task ':app:transformNativeLibsWithMergeJniLibsForDebug'.
> More than one file was found with OS independent path 'lib/x86/libc++_shared.so'

* Try:
Run with --stacktrace option to get the stack trace. Run with --info or --debug option to get more log output. Run with --scan to get full insights.

* Get more help at https://help.gradle.org

steps to reproduce:

  1. use @expo bare typescript generator
  2. yarn add @notifee/react-native
  3. react-native run-android

SOLUTION ✅ (taken from nonotest's reply here ) :

app\build.grade

android {
....
packagingOptions {
       pickFirst 'lib/x86/libc++_shared.so'
       pickFirst 'lib/x86_64/libjsc.so'
       pickFirst 'lib/arm64-v8a/libjsc.so'
       pickFirst 'lib/arm64-v8a/libc++_shared.so'   <-------------- 💡
       pickFirst 'lib/x86_64/libc++_shared.so'
       pickFirst 'lib/armeabi-v7a/libc++_shared.so'
   }
....
}

hope this helps

default/custom sound is not working

I'm trying to set a custom notification sound to my app. I have an mp3 file that I'm trying to use as the sound.

I tried adding the mp3 file to the res/raw directory, and then passing the reference to the

    // Create a channel 
    const channelId = await notifee.createChannel({
      id: 'Firabsev6',
      name: 'Firabsev6',
      sound: 'glass'
    });

    // Display a notification
    await notifee.displayNotification({
      title: 'Notification Title 3',
      body: 'Main body content of the notification',
      android: {
        channelId,
        sound: 'glass'
      },
    });

I tried to look for a guide in the documentation, but little was said about custom notifications sound.
Any idea on how to make this work?
And also default notification sound is not working as well ?

Creating a group with a channel fails with "NotificationChannelGroup doesn't exist"

Code

const groupId = await notifee.createChannelGroup({
    id: 'test_group',
    name: 'Test group',
  });

  const channelId = await notifee.createChannel({
    id: 'test_channel',
    name: 'Test Channel',
    groupId: 'test_group',
  });

Exception:

Error: NotificationChannelGroup doesn't exist at Object.fn [as createChannel]
at NotifeeApiModule.createChannel
at onMessageReceived
...

Running Android emulator, Android9_Nexus_6_API_28...

Documentation says it should work: https://notifee.app/react-native/docs/android/channels#creating-updating-groups

using launch activity resets my app

Android:

When the users minimizes the app they immediately get a notification.
If they click on that notification the app won't open unless I set
launchActivity: "default"
but when that happens the app opens up in like new, losing all of my state and router history

This is how I fire the notification:

notifee.displayNotification({
	title: "Pathboks",
	body: "Continue Reading...",
	data: {
		pathbook: pathbook.id,
	},
	android: {
		channelId,
		pressAction: {
			id: "default",
			launchActivity: "default",
		 },
	},
});

And this is how I handle it:

notifee.onBackgroundEvent(async ({ type, detail }) => {
	const pathbook = detail.notification.data.pathbook;
	 if (type === EventType.ACTION_PRESS && pathbook) {
		NavigationService.navigate("Pathbook", { pathbookID: pathbook });
	}
});

If you need to know, I am using React Navigation and the Navigation Service pretty much just takes you to a certain page with parameters.

To summarize:
The notification won't bring up the app unless I set launchActivity but doing so resets the app and loads it fresh.

Suggestion, maybe there is a better way to open the app(?)

setBackgroundMessageHandler() is unsupported

I'm using React-native-firebase.I tried to integrat with notifee. when I try to change displayed notification rnfirebase to notifee. notifee notification which has action buttons.

Error:_ firebase.messaging().setBackgroundMessageHandler() is unsupported by the native Firebase SDKs.

Messaging#setBackgroundMessageHandler
    index.js:136:20
FlatList.props.ItemSeparatorComponent
    Notifications.js:255:40
loadModuleImplementation
    require.js:322:6
RadioButtonLabel#constructor
    SimpleRadioButton.js:259:19
loadModuleImplementation
    require.js:322:6
<unknown>
    index.bundle?platform=ios&dev=true&minify=false:166534:58
loadModuleImplementation
    require.js:322:6
<global>
    App.js:11
loadModuleImplementation
    require.js:322:6
<global>
    index.js:7
loadModuleImplementation
    require.js:322:6
guardedLoadModule
    require.js:201:45
render
    StoreCapacityModal.js:34:16

current code,

export async function onMessageReceived(message) {
  const { type} = message.data;
  setCategories();
    await notifee.displayNotification({
        title: 'Bildirim',
        description: 'Bildirim geliyo çok iyi!',
        android: {
          channelId: 'bildirim',
          actions: [
            {
              title: 'Personel Yok',
              pressAction: {
                id: 'btn1',
              },
            },
            {
              title: 'Gereksiz Bildirim',
              pressAction: {
                id: 'btn2',
              },
            },
          ],
        },
      });
       notifee.onForegroundEvent(({ type, detail }) => {
        if (type === EventType.ACTION_PRESS && detail.pressAction.id === "btn1") {
          alert("Button 1 e basıldı.")
        }
        if (type === EventType.ACTION_PRESS && detail.pressAction.id === "btn2") {
          alert("Button 2 ye basıldı.")
        }
      });
      notifee.onBackgroundEvent(async ({ type, detail }) => {
        if (type === EventType.ACTION_PRESS && detail.pressAction.id === "btn1") {
            alert("Button 1 e basıldı.")
          }
          if (type === EventType.ACTION_PRESS && detail.pressAction.id === "btn2") {
            alert("Button 2 ye basıldı.")
          }
    });
}
async function setCategories() {
  await notifee.setNotificationCategories([
    {
      id: 'post',
      actions: [
        {
          id: 'btn1',
          title: 'Personel Yok',
        },
        {
          id: 'btn2',
          title: 'Gereksiz Bildirim',
        }
      ],
      ios: {
        categoryId: 'post',
      },
    },
  ]);
}

firebase.messaging().onMessage(onMessageReceived);
firebase.messaging().setBackgroundMessageHandler(onMessageReceived);


Require local image throws error for Android largeIcon

Hey there!

The library is looking fantastic at the moment but there is one issue that I've run into recently. When using a local image for largeIcon, an error is thrown asking for a string. I've attached incredibly basic code below. This is through the function notifee.displayNotification

android: {
            channelId: 'message',
            timestamp: Date.now(),
            showTimestamp: true,
            largeIcon: require('./Images/logo.png') // This throws the error "notifee.displayNotification(*) 'notification.android.largeIcon' expected a string value."
          },

There is no pop up notification in foreground on Android

Just use the sample code and send the notification from Firebase console. It work, but there is no pop up on Android.

Version:

  "dependencies": {
    "@notifee/react-native": "^0.4.0",
    "@react-native-firebase/app": "^6.7.1",
    "@react-native-firebase/messaging": "^6.7.1",
    "react": "16.8.6",
    "react-native": "0.60.5"
  },

Sample code:

    // Create a channel 
      const channelId = await notifee.createChannel({
        id: 'default',
        name: 'Default Channel',
      });
      
      await notifee.displayNotification({
        title: title,
        body: body,
        android: {
          channelId,
        },
      });
    });

I can get the notification on status bar. But there is no pop up notification like IOS.

I suppose I have a notification dialog on the red zone.
截圖 2020-05-04 下午3 37 24

Do I miss some steps or I have to use some libraries to achieve it ?

[Android] Open application on notification press

Hi,

I can't figure out how to the open the app when it's in background / quit state and the user press a notification.

My notifcations partern is the folowing (on background / quite state):

  • App receives a silent notification;
  • App treats the silent notification (fectching data + some other stuffs);
  • App generate a local notification to be displayed;

Everything works fine exept that the local notification can not be press, or at least pressing it doesn't open the app, whatever its state is.

The notification object look like this:

let nofifData = {
        title: "title",
        body : "body",
        id: notifId.toString(),
        data : { conv_key: data.conv_key},
        android: {
            channelId : 'myAppChannel',
            autoCancel : true,
            color : "#72CDCF",
            importance : Importance.HIGH,
            smallIcon : "ic_notification",
            sound: localPref.sound ? "default" : '',
            badgeCount : getBadgeCount(),
            pressAction: {
                id: "default",
            },
        }
    };

By the way, when I press the notification, i get in the logs a warning:
No task registered for key app.notifee.notification.event
I'm not sure it's related but well, it doest hurt mentionning it...

Thanks in advance for any help (and for the library !)

Worth mentionning (or not) that I'm also using

  • Firebase Cloud Messaging
  • wix/react-native-navigation
  • RN 62.2
  • notifee : 0.4.0

CocoaPods could not find compatible versions for pod "RNNotifee":

Hi,

Issue after installing react native plugin and try to install pods.

[!] CocoaPods could not find compatible versions for pod "RNNotifee":
In Podfile:
RNNotifee (from ../node_modules/@notifee/react-native)

Specs satisfying the RNNotifee (from ../node_modules/@notifee/react-native) dependency were found, but they required a higher minimum deployment target.

Crash when proguardrules is set to true

Hello.
I get this crash when i set proguardrules to true.
Any idea ?
Thank you.

Crashlytics
Unable to get provider io.invertase.notifee.NotifeeInitProvider: org.greenrobot.eventbus.g: Subscriber class app.notifee.core.database.Database_Impl and its super classes have no public methods with the @Subscribe annotation

notification badge support

Hello, I just purchased the package then realized the package doesn't support notification badge.
So far I know there few but it seems like none of them are up to date and wondering any plan to add such functionality.
Even without the badge func. this is a great package and really loves it and also huge fun of the idea of charging the package. Hope the team the best.

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.