ReactNative AppPush Setup
Native Prerequisites
Complete the following Native AppPush Prerequisites:
• Android Key Retrieval section and Certificate Upload section.
• Android App Setup Section step 3 only.
• iOS Certificate Retrieval section and Certificate Upload section.
• iOS App Setup Section steps 1 and 2 only.
App Setup
1. Install the Push Notification Package
First, install the React Native Push Notification package:
npm install --save react-native-push-notification
# or
yarn add react-native-push-notification
2. Update Android Configuration
Update MainApplication.java
Add the Push Notification package to your list of packages:
import com.dieam.reactnativepushnotification.ReactNativePushNotificationPackage;
class MainApplication extends Application implements ReactApplication {
private final ReactNativeHost mReactNativeHost = new ReactNativeHost(this) {
@Override
protected List<ReactPackage> getPackages() {
@SuppressWarnings("UnnecessaryLocalVariable")
List<ReactPackage> packages = new PackageList(this).getPackages();
// Add the push notification package
packages.add(new ReactNativePushNotificationPackage());
return packages;
}
};
}
Update android/app/build.gradle
Add the push notification dependency:
dependencies {
implementation project(':react-native-push-notification')
}
Update android/settings.gradle
Add the push notification project:
include ':react-native-push-notification'
project(':react-native-push-notification').projectDir = new File(rootProject.projectDir, '../node_modules/react-native-push-notification/android')
3. Configure Push Notifications in JavaScript
Create a Push Notification service file (e.g., PushNotificationService.js
):
import PushNotification from 'react-native-push-notification';
import PushNotificationIOS from '@react-native-community/push-notification-ios';
import { Platform } from 'react-native';
import { Wunderkind } from '@wunderkind-sdk-react/react-native-wunderkind-sdk';
class PushNotificationService {
configure = () => {
// Configure push notifications
PushNotification.configure({
// (required) Called when a remote or local notification is opened or received
onNotification: function(notification) {
console.log('NOTIFICATION:', notification);
// Process the notification
const data = notification.data || {};
// Check if it's a Wunderkind notification
if (data.wunderkindData) {
// Track push notification delivered and opened
Wunderkind.trackAppPushDelivered(data);
Wunderkind.trackAppPushOpened(data);
// Handle item IDs if present
if (data.wunderkindItemIds) {
const itemIds = data.wunderkindItemIds.split(',');
console.log('Wunderkind Item IDs:', itemIds);
// Process item IDs as needed
}
}
// Required on iOS
notification.finish(PushNotificationIOS.FetchResult.NoData);
},
// (optional) Called when Token is generated
onRegister: function(token) {
console.log('TOKEN:', token);
if (token && token.token) {
// Track the token with Wunderkind
Wunderkind.trackAppPushTokenSet(token.token);
}
},
// (optional) Called when the user fails to register for remote notifications
onRegistrationError: function(err) {
console.error(err.message, err);
// Notify user that push notifications are disabled
Wunderkind.trackAppPushOptOut();
},
// Should the initial notification be popped automatically
popInitialNotification: true,
// Request permissions on iOS
requestPermissions: true,
});
// Configure local notifications (for Android)
PushNotification.createChannel(
{
channelId: 'wunderkind-channel',
channelName: 'Wunderkind Notifications',
channelDescription: 'Notifications from Wunderkind',
soundName: 'default',
importance: 4, // Importance level (4 is high)
vibrate: true,
},
(created) => console.log(`Channel created: ${created}`)
);
}
// Request permission and track opt-in status
requestNotificationPermissions = async () => {
// For iOS, the permission request is handled by PushNotification.configure
// For Android, check and request permissions based on API level
if (Platform.OS === 'android') {
try {
const granted = await PermissionsAndroid.request(
PermissionsAndroid.PERMISSIONS.POST_NOTIFICATIONS,
{
title: 'Push Notification Permission',
message: 'App needs permission to receive push notifications',
buttonNeutral: 'Ask Me Later',
buttonNegative: 'Cancel',
buttonPositive: 'OK',
},
);
if (granted === PermissionsAndroid.RESULTS.GRANTED) {
console.log('Notification permission granted');
Wunderkind.trackAppPushOptIn();
} else {
console.log('Notification permission denied');
Wunderkind.trackAppPushOptOut();
}
} catch (err) {
console.warn(err);
Wunderkind.trackAppPushOptOut();
}
}
}
// Check if notifications are enabled
checkPermission = async () => {
if (Platform.OS === 'ios') {
const authStatus = await PushNotificationIOS.checkPermissions();
if (authStatus.alert || authStatus.badge || authStatus.sound) {
Wunderkind.trackAppPushOptIn();
} else {
Wunderkind.trackAppPushOptOut();
}
}
// For Android, we check in the requestNotificationPermissions method
}
}
export default new PushNotificationService();
4. Initialize the Push Notification Service
In your main app file (e.g., App.js
or index.js
):
import React, { useEffect } from 'react';
import { AppState, Platform } from 'react-native';
import PushNotificationService from './PushNotificationService';
import { Wunderkind } from '@wunderkind-sdk-react/react-native-wunderkind-sdk';
const App = () => {
useEffect(() => {
// Initialize Wunderkind SDK
Wunderkind.initializeSdk(YOUR_WEBSITE_ID, true);
// Configure push notifications
PushNotificationService.configure();
// Request permissions and track opt-in status
PushNotificationService.requestNotificationPermissions();
// Check permission status when the app comes to the foreground
const handleAppStateChange = (nextAppState) => {
if (nextAppState === 'active') {
PushNotificationService.checkPermission();
}
};
const subscription = AppState.addEventListener('change', handleAppStateChange);
return () => {
subscription.remove();
};
}, []);
// Rest of your app code
};
export default App;
Updated about 1 month ago