Closed masterial closed 3 years ago
@masterial we're having the same issue here, did you figure a solution?
@Zeneixe Yes, https://github.com/unblockable/react-native-pusher-push-notifications/tree/2.2.0-pusher. Basically, I had to implement the setUserId logic to make it work.
Nice thanks, will have a look at the code, but it seems to be an android-only solution right?
Hey, above page is giving a 404 now. Anyway, is there still no bridge here for the Beams Token provider client SDK logic from native to JS? I want to not just send push notifications based on device interest, but also to authenticated users. My server's in node but client is in rct native JS and a JS client SDK does not seem to exist based on the Official Authenticated User docs from pusher. Any help would be greatly appreciated community.
@irajwani Any progress on this since you posted last July?
Hey @alxmrtnz I stopped using this feature from Pusher as I figured out how to implement push notifications through r-n-firebase. I suggest you do the same with RN version 0.61.+, and then make an express server app to send push notifications to users based on their FCM tokens that you've got stored in your cloud database for each user.
Thanks for the follow up @irajwani . Appreciate it!
Hi, maybe someone has solution how to add "Publish to a specific User" with pusher to react-native?
@nikita-filimonau I'm not sure how much this will help, but this is how we ended up publishing to a specific user when they log into our React Native app.
There was some setup necessary in native code both for iOS and Android that goes beyond the following, but I hope it helps.
We created a <PushNotifications />
React component that we import into our app's primary navigator (we used react-navigation) and it takes care of initializing Pusher and sets a user when they're logged into our app. I added notes that I hope also help:
import * as React from 'react';
import { PUSHER_BEAMS_INSTANCE_ID } from 'react-native-dotenv';
import RNPusherPushNotifications from 'react-native-pusher-push-notifications';
import { Platform } from 'react-native';
import { connect } from 'react-redux';
import API from './api';
// Test Interests
const interests = [
'debug-test',
'debug-secondtest',
]
// This is a custom hook to reference the previous state
// of a variable (in this file, used to check previous state
// of `authToken`)
function usePrevious(value) {
const { useRef, useEffect } = React;
const ref = useRef();
useEffect(() => {
ref.current = value;
});
return ref.current;
}
function PusherNotifications({
user,
authToken,
}) {
const { useEffect } = React;
const prevAuthToken = usePrevious(authToken);
useEffect(() => {
if (authToken && user) {
initializePusher();
}
if (
!authToken
&& prevAuthToken
&& authToken !== prevAuthToken
) {
// Here, we keep track of changes to our authToken (stored in Redux).
// If the authToken changes and no longer exists, as well as the previous
// state of the authToken (prevAuthToken) being different than the new
// authToken, we know that authToken has been reset and the user has
// signed out.
//
// When user signs out, we need to clear the Pusher notification state
// with `clearAllState()`
if (RNPusherPushNotifications) {
RNPusherPushNotifications.clearAllState();
}
}
}, [authToken])
function onPusherInitError(statusCode, response) {
console.log('Error: PUSHER statusCode: ', statusCode);
console.log('Error: PUSHER response: ', response);
}
function onPusherInitSuccess(response) {
console.log('PUSHER SUCCESS: ', response);
}
async function initializePusher() {
try {
// Here you need to get a generated pusher token from your API
// This requires backend setup separate from the frontend React Native
//
// See Step 4 of this section on Authentications:
// https://pusher.com/docs/beams/concepts/authenticated-users#authentication-process
const response = await API.getPusherToken(authToken)
if (response.ok) {
const { token } = response.data;
// Set your app key and register for push
// Store your Pusher Instance ID in an environment variable, import it
// and use it here.
// We used react-native-dotenv for .env variable storage
RNPusherPushNotifications.setInstanceId(PUSHER_BEAMS_INSTANCE_ID);
// Init interests after registration
RNPusherPushNotifications.on('registered', () => {
// This subscribes to general interests. Notifications triggered using
// instances will be used for all users, not targeting a specific user.
interests.forEach((interest) => {
subscribe(interest);
});
// setUser takes our logged in user's `id` attribute and appends `user-` as our
// backend is setup with Pusher to setUsers using this naming convention (ie. user-214 would
// be an example user for this function)
setUser(`user-${user.id}`, token, onPusherInitError, onPusherInitSuccess)
});
// Setup notification listeners
// RNPusherPushNotifications.on('notification', handleNotification);
RNPusherPushNotifications.on('notification', (notification) => {
handleNotification({ notification })
});
}
} catch (e) {
console.log('error getting pusher token: ', e)
}
}
function subscribe(interest) {
// console.log('subscribing to interest... ', interest);
// Note that only Android devices will respond to success/error callbacks
RNPusherPushNotifications.subscribe(
interest,
(statusCode, response) => {
console.error(statusCode, response);
},
() => {
console.log(`Subscribed to ${interest}`);
}
);
}
function setUser(userId, token, onError, onSuccess) {
// Note that only Android devices will respond to success/error callbacks
RNPusherPushNotifications.setUserId(
userId,
token,
(statusCode, response) => {
onError(statusCode, response);
},
() => {
onSuccess('Set User ID Success');
}
);
}
function handleNotification({ notification }) {
// Handle notifications received while app is open
const alert = Platform.OS === 'ios'
? notification.userInfo.aps.alert
: notification;
console.log('alert: ', alert);
// iOS app specific handling
if (Platform.OS === 'ios') {
switch (notification.appState) {
case 'inactive':
// inactive: App came in foreground by clicking on notification.
// Use notification.userInfo for redirecting to specific view controller
break;
case 'background':
// background: App is in background and notification is received.
// You can fetch required data here don't do anything with UI
break;
case 'active':
// App is foreground and notification is received. Show an alert or something.
break;
default:
break;
}
}
};
return null;
}
// We use Redux to store the logged in user's profile data and auth token,
// allowing us to pass it as a prop to this PusherNotifications component
//
// We then import <PusherNotifications /> into our main navigator (react-navigation)
// so that it is within the Redux wrapper (otherwise we'd put it in App.js)
const mapStateToProps = ({ user, authToken }) => ({
user,
authToken,
});
export default connect(
mapStateToProps,
null
)(PusherNotifications);
@alxmrtnz Thanks a lot! It really help!
@alxmrtnz What is the native code you added to make the above component works?
@AhmSaeed
Here's what we did, according to install docs:
As written in the install docs, we added this code to AppDelegate.m
. Here's our AppDelegate.m:
/**
* Copyright (c) Facebook, Inc. and its affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/
#import "AppDelegate.h"
#import <RNPusherPushNotifications.h>
#import <React/RCTBridge.h>
#import <React/RCTBundleURLProvider.h>
#import <React/RCTRootView.h>
#import "RNSplashScreen.h" // here
#import <AppCenterReactNative.h>
#import <AppCenterReactNativeAnalytics.h>
#import <AppCenterReactNativeCrashes.h>
@implementation AppDelegate
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
RCTBridge *bridge = [[RCTBridge alloc] initWithDelegate:self launchOptions:launchOptions];
RCTRootView *rootView = [[RCTRootView alloc] initWithBridge:bridge
moduleName:@"myTeamChannelReactNative"
initialProperties:nil];
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];
[AppCenterReactNative register];
[AppCenterReactNativeAnalytics registerWithInitiallyEnabled:true];
[AppCenterReactNativeCrashes registerWithAutomaticProcessing];
[RNSplashScreen show];
return YES;
}
- (NSURL *)sourceURLForBridge:(RCTBridge *)bridge
{
#if DEBUG
return [[RCTBundleURLProvider sharedSettings] jsBundleURLForBundleRoot:@"index" fallbackResource:nil];
#else
return [[NSBundle mainBundle] URLForResource:@"main" withExtension:@"jsbundle"];
#endif
}
// Add the following as a new methods to AppDelegate.m
- (void)application:(UIApplication *)application didRegisterForRemoteNotificationsWithDeviceToken:(NSData *)deviceToken {
NSLog(@"Registered for remote with token: %@", deviceToken);
[[RNPusherPushNotifications alloc] setDeviceToken:deviceToken];
}
- (void)application:(UIApplication *)application didReceiveRemoteNotification:(NSDictionary *)userInfo fetchCompletionHandler:(void (^)(UIBackgroundFetchResult))completionHandler {
[[RNPusherPushNotifications alloc] handleNotification:userInfo];
}
-(void)application:(UIApplication *)application didFailToRegisterForRemoteNotificationsWithError:(NSError *)error {
NSLog(@"Remote notification support is unavailable due to error: %@", error.localizedDescription);
}
@end
We followed installation instructions here. Here are the resulting files:
android/build.gradle
buildscript {
ext {
buildToolsVersion = "28.0.3"
minSdkVersion = 23
compileSdkVersion = 28
targetSdkVersion = 28
}
repositories {
google()
jcenter()
}
dependencies {
classpath('com.android.tools.build:gradle:4.0.0')
classpath("com.google.gms:google-services:4.3.0")
// NOTE: Do not place your application dependencies here; they belong
// in the individual module build.gradle files
}
}
allprojects {
repositories {
mavenLocal()
maven {
// All of React Native (JS, Obj-C sources, Android binaries) is installed from npm
url("$rootDir/../node_modules/react-native/android")
}
maven {
// Android JSC is installed from npm
url("$rootDir/../node_modules/jsc-android/dist")
}
maven { url 'https://maven.google.com' }
google()
jcenter()
maven { url 'https://jitpack.io' }
}
}
and
android/app/build.gradle
:
apply plugin: "com.android.application"
import com.android.build.OutputFile
/**
* The react.gradle file registers a task for each build variant (e.g. bundleDebugJsAndAssets
* and bundleReleaseJsAndAssets).
* These basically call `react-native bundle` with the correct arguments during the Android build
* cycle. By default, bundleDebugJsAndAssets is skipped, as in debug/dev mode we prefer to load the
* bundle directly from the development server. Below you can see all the possible configurations
* and their defaults. If you decide to add a configuration block, make sure to add it before the
* `apply from: "../../node_modules/react-native/react.gradle"` line.
*
* project.ext.react = [
* // the name of the generated asset file containing your JS bundle
* bundleAssetName: "index.android.bundle",
*
* // the entry file for bundle generation
* entryFile: "index.android.js",
*
* // https://facebook.github.io/react-native/docs/performance#enable-the-ram-format
* bundleCommand: "ram-bundle",
*
* // whether to bundle JS and assets in debug mode
* bundleInDebug: false,
*
* // whether to bundle JS and assets in release mode
* bundleInRelease: true,
*
* // whether to bundle JS and assets in another build variant (if configured).
* // See http://tools.android.com/tech-docs/new-build-system/user-guide#TOC-Build-Variants
* // The configuration property can be in the following formats
* // 'bundleIn${productFlavor}${buildType}'
* // 'bundleIn${buildType}'
* // bundleInFreeDebug: true,
* // bundleInPaidRelease: true,
* // bundleInBeta: true,
*
* // whether to disable dev mode in custom build variants (by default only disabled in release)
* // for example: to disable dev mode in the staging build type (if configured)
* devDisabledInStaging: true,
* // The configuration property can be in the following formats
* // 'devDisabledIn${productFlavor}${buildType}'
* // 'devDisabledIn${buildType}'
*
* // the root of your project, i.e. where "package.json" lives
* root: "../../",
*
* // where to put the JS bundle asset in debug mode
* jsBundleDirDebug: "$buildDir/intermediates/assets/debug",
*
* // where to put the JS bundle asset in release mode
* jsBundleDirRelease: "$buildDir/intermediates/assets/release",
*
* // where to put drawable resources / React Native assets, e.g. the ones you use via
* // require('./image.png')), in debug mode
* resourcesDirDebug: "$buildDir/intermediates/res/merged/debug",
*
* // where to put drawable resources / React Native assets, e.g. the ones you use via
* // require('./image.png')), in release mode
* resourcesDirRelease: "$buildDir/intermediates/res/merged/release",
*
* // by default the gradle tasks are skipped if none of the JS files or assets change; this means
* // that we don't look at files in android/ or ios/ to determine whether the tasks are up to
* // date; if you have any other folders that you want to ignore for performance reasons (gradle
* // indexes the entire tree), add them here. Alternatively, if you have JS files in android/
* // for example, you might want to remove it from here.
* inputExcludes: ["android/**", "ios/**"],
*
* // override which node gets called and with what additional arguments
* nodeExecutableAndArgs: ["node"],
*
* // supply additional arguments to the packager
* extraPackagerArgs: []
* ]
*/
project.ext.react = [
entryFile: "index.js",
enableHermes: false, // clean and rebuild if changing
]
apply from: "../../node_modules/react-native/react.gradle"
/**
* Set this to true to create two separate APKs instead of one:
* - An APK that only works on ARM devices
* - An APK that only works on x86 devices
* The advantage is the size of the APK is reduced by about 4MB.
* Upload all the APKs to the Play Store and people will download
* the correct one based on the CPU architecture of their device.
*/
def enableSeparateBuildPerCPUArchitecture = false
/**
* Run Proguard to shrink the Java bytecode in release builds.
*/
def enableProguardInReleaseBuilds = false
/**
* The preferred build flavor of JavaScriptCore.
*
* For example, to use the international variant, you can use:
* `def jscFlavor = 'org.webkit:android-jsc-intl:+'`
*
* The international variant includes ICU i18n library and necessary data
* allowing to use e.g. `Date.toLocaleString` and `String.localeCompare` that
* give correct results when using with locales other than en-US. Note that
* this variant is about 6MiB larger per architecture than default.
*/
def jscFlavor = 'org.webkit:android-jsc:+'
/**
* Whether to enable the Hermes VM.
*
* This should be set on project.ext.react and mirrored here. If it is not set
* on project.ext.react, JavaScript will not be compiled to Hermes Bytecode
* and the benefits of using Hermes will therefore be sharply reduced.
*/
def enableHermes = project.ext.react.get("enableHermes", false);
android {
compileSdkVersion rootProject.ext.compileSdkVersion
compileOptions {
sourceCompatibility JavaVersion.VERSION_1_8
targetCompatibility JavaVersion.VERSION_1_8
}
defaultConfig {
applicationId "com.myteamchannel.teamapp"
minSdkVersion rootProject.ext.minSdkVersion
targetSdkVersion rootProject.ext.targetSdkVersion
versionCode 2020010541
versionName "2020.6.04"
vectorDrawables.useSupportLibrary = true
multiDexEnabled true
}
splits {
abi {
reset()
enable enableSeparateBuildPerCPUArchitecture
universalApk false // If true, also generate a universal APK
include "armeabi-v7a", "x86", "arm64-v8a", "x86_64"
}
}
signingConfigs {
debug {
storeFile file('debug.keystore')
storePassword 'android'
keyAlias 'androiddebugkey'
keyPassword 'android'
}
}
buildTypes {
debug {
signingConfig signingConfigs.debug
}
release {
// Caution! In production, you need to generate your own keystore file.
// see https://facebook.github.io/react-native/docs/signed-apk-android.
signingConfig signingConfigs.debug
minifyEnabled enableProguardInReleaseBuilds
proguardFiles getDefaultProguardFile("proguard-android.txt"), "proguard-rules.pro"
}
}
// applicationVariants are e.g. debug, release
applicationVariants.all { variant ->
variant.outputs.each { output ->
// For each separate APK per architecture, set a unique version code as described here:
// https://developer.android.com/studio/build/configure-apk-splits.html
def versionCodes = ["armeabi-v7a": 1, "x86": 2, "arm64-v8a": 3, "x86_64": 4]
def abi = output.getFilter(OutputFile.ABI)
if (abi != null) { // null for the universal-debug, universal-release variants
output.versionCodeOverride =
versionCodes.get(abi) * 1048576 + defaultConfig.versionCode
}
}
}
}
dependencies {
implementation project(':react-native-wheel-picker-android')
implementation fileTree(dir: "libs", include: ["*.jar"])
implementation "com.facebook.react:react-native:+" // From node_modules
implementation 'com.google.firebase:firebase-messaging:18.0.0'
implementation project(':react-native-pusher-push-notifications')
implementation 'com.pusher:push-notifications-android:1.6.2'
implementation 'com.android.support:multidex:1.0.3'
if (enableHermes) {
def hermesPath = "../../node_modules/hermes-engine/android/";
debugImplementation files(hermesPath + "hermes-debug.aar")
releaseImplementation files(hermesPath + "hermes-release.aar")
} else {
implementation jscFlavor
}
}
// Run this once to be able to run the application with BUCK
// puts all compile dependencies into folder libs for BUCK to use
task copyDownloadableDepsToLibs(type: Copy) {
from configurations.compile
into 'libs'
}
apply from: file("../../node_modules/@react-native-community/cli-platform-android/native_modules.gradle"); applyNativeModulesAppBuildGradle(project)
apply from: "../../node_modules/react-native-vector-icons/fonts.gradle"
apply plugin: 'com.google.gms.google-services'
MainApplication.java
:
package com.myteamchannel.teamapp;
import com.b8ne.RNPusherPushNotifications.RNPusherPushNotificationsPackage;
import android.app.Application;
import android.content.Context;
import com.facebook.react.PackageList;
import com.facebook.react.ReactApplication;
import com.facebook.react.ReactNativeHost;
import com.facebook.react.ReactPackage;
import com.facebook.soloader.SoLoader;
import java.lang.reflect.InvocationTargetException;
import java.util.List;
public class MainApplication extends Application implements ReactApplication {
private final ReactNativeHost mReactNativeHost =
new ReactNativeHost(this) {
@Override
public boolean getUseDeveloperSupport() {
return BuildConfig.DEBUG;
}
@Override
protected List<ReactPackage> getPackages() {
@SuppressWarnings("UnnecessaryLocalVariable")
List<ReactPackage> packages = new PackageList(this).getPackages();
// Packages that cannot be autolinked yet can be added manually here, for example:
// packages.add(new MyReactNativePackage());
packages.add(new RNPusherPushNotificationsPackage());
return packages;
}
@Override
protected String getJSMainModuleName() {
return "index";
}
};
@Override
public ReactNativeHost getReactNativeHost() {
return mReactNativeHost;
}
@Override
public void onCreate() {
super.onCreate();
SoLoader.init(this, /* native exopackage */ false);
initializeFlipper(this); // Remove this line if you don't want Flipper enabled
}
/**
* Loads Flipper in React Native templates.
*
* @param context
*/
private static void initializeFlipper(Context context) {
if (BuildConfig.DEBUG) {
try {
/*
We use reflection here to pick up the class that initializes Flipper,
since Flipper library is not available in release mode
*/
Class<?> aClass = Class.forName("com.facebook.flipper.ReactNativeFlipper");
aClass.getMethod("initializeFlipper", Context.class).invoke(null, context);
} catch (ClassNotFoundException e) {
e.printStackTrace();
} catch (NoSuchMethodException e) {
e.printStackTrace();
} catch (IllegalAccessException e) {
e.printStackTrace();
} catch (InvocationTargetException e) {
e.printStackTrace();
}
}
}
}
I find it helpful when seeing full files of what's working for other people, so I hope this helps! For the other files listed in the install docs, just follow those docs as that's what we have impletmented.
Stack:
"react-native": "0.62.2",
"react-native-pusher-push-notifications": "^2.4.0",
@alxmrtnz I am doing the same but keep getting the error on this code
if (RNPusherPushNotifications) {
RNPusherPushNotifications.clearAllState();
}
Attempt to invoke virtual method 'void com.b8ne.RNPusherPushNotifications.PusherWrapper.clearAllState()' on a null object reference
Sorry, @Ahmdrza . I'm really not sure on that one :/
@Ahmdrza
Hi, it looks like you call
RNPusherPushNotifications.clearAllState();
Before this:
RNPusherPushNotifications.setInstanceId
or this
RNPusherPushNotifications.on('registered', () => { ...
RNPusherPushNotifications.subscribe( ...
Where are we at with this issue @masterial? It looks like this has turned more into a feature request for an API to assist in setting the user id?
@Humni why is this issue closed? what was the net result of this?
@hsavit1 it's a very stale issue which the users likely have forgotten - without more information from the OP it won't be possible to progress this ticket further. If more information is provided I'll happily re-open it
getPusherToken
Hey @alxmrtnz !
Can you just explain to me what is the API.getPusherToken(token)
is?
Seems like it's not possible to send targeted device notifications with this library. Am I right?
For reference: https://pusher.com/docs/beams/reference/android#-setuserid