Skip to content

Latest commit

 

History

History
493 lines (415 loc) · 15.2 KB

PushNotifications.md

File metadata and controls

493 lines (415 loc) · 15.2 KB
banner-react-native-push

Push Notifications

The easiest way to support push notifications in your app.

Features

Feature Description iOS Android
Automatic Token Management Push notification tokens automatically sync to the Courier studio.
Notification Tracking Track if your users received or clicked your notifications even if your app is not runnning or open.
Permission Requests & Checking Simple functions to request and check push notification permission settings.

Requirements

Requirement Reason
Authentication Needs Authentication to sync push notification device tokens to the current user and Courier.
A Configured Provider Courier needs to know who to route the push notifications to so your users can receive them.

Provider iOS Token Sync Android Token Sync
(APNS) - Apple Push Notification Service Automatic Not Supported
(FCM) - Firebase Cloud Messaging Manual Automatic
OneSignal Manual Manual
Expo Manual Manual

Manual Token Syncing

To manually sync tokens, use the following code.

// To set the token in the Courier
await Courier.shared.setToken({
  key: 'YOUR_PROVIDER',
  token: 'example_token'
});

// Or

await Courier.shared.setTokenForProvider({
  provider: CourierPushProvider.EXPO,
  token: 'example_token'
});

// To get the token stored in the SDK
// This does not get it from the Courier API, just from the SDK's local storage
const tokenForProvider = await Courier.shared.getTokenForProvider({
  provider: CourierPushProvider.EXPO
});

// Or

const tokenForKey = await Courier.shared.getToken({
  key: 'YOUR_PROVIDER'
});

Automatic Token Syncing

To allow the Courier SDK to automatically sync tokens, use the following steps.

iOS Setup

Requirement Reason
Apple Developer Membership Apple requires all iOS developers to have a membership so you can manage your push notification certificates.
A phyical iOS device Although you can setup the Courier SDK without a device, a physical device is the only way to fully ensure push notification tokens and notification delivery is working correctly. Simulators are not reliable.

1. Enable the "Push Notifications" capability

Enable.push.notification.mov
  1. Select your Xcode project file
  2. Click your project Target
  3. Click "Signing & Capabilities"
  4. Click the small "+" to add a capability
  5. Press Enter

2. Support Notification Callbacks and Automatic APNS Token syncing

In Xcode, change your AppDelegate.h to use this snippet.

#import <courier-react-native/CourierReactNativeDelegate.h>

@interface AppDelegate : CourierReactNativeDelegate
@end

3. Add the Notification Service Extension (Optional, but recommended)

To make sure Courier can track when a notification is delivered to the device, you need to add a Notification Service Extension. Here is how to add one.

ios-notification-service-extension.mov
  1. Download and Unzip the Courier Notification Service Extension: CourierNotificationServiceTemplate.zip
  2. Open the folder in terminal and run sh make_template.sh
    • This will create the Notification Service Extension on your mac to save you time
  3. Open your iOS app in Xcode and go to File > New > Target
  4. Select "Courier Service" and click "Next"
  5. Give the Notification Service Extension a name (i.e. "CourierService").
  6. Click Finish
  7. Go into your CourierService target > Build Settings > Search "ENABLE_USER"
  8. Set "User Script Sandboxing" to "No"

Link the Courier SDK to your extension:

  1. Add the following snippet to the bottom of your Podfile
target 'CourierService' do
    pod 'Courier_iOS'
end
  1. Run pod install

Android Setup

Requirement Reason
Firebase Account Needed to send push notifications out to your Android devices. Courier recommends you do this for the most ideal developer experience.
A phyical Android device Although you can setup the Courier SDK without a physical device, a physical device is the best way to fully ensure push notification tokens and notification delivery is working correctly. Simulators are not reliable.

1. Add Firebase

react-native-android-dependency-setup.mov
  1. Open Android project
  2. Register your app in Firebase and download your google-services.json file
  3. Add the google-services.json file to your yourApp/app/src directory
  4. Add the google-services dependency to your yourApp/android/build.gradle file:
buildscript {
  dependencies {
    ..
    classpath("com.google.gms:google-services:4.3.14") // Add this line
  }
}
  1. Add this following line to the top of your /android/app/build.gradle file:
apply plugin: "com.android.application"
apply plugin: "com.google.gms.google-services" // Add this line
  1. Run Gradle Sync

2. Support Notification Callbacks and Automatic FCM Token syncing

react-native-android-service-setup.mov
  1. Change your MainActivity to extend the CourierReactNativeActivity
    • This allows Courier to handle when push notifications are delivered and clicked
  2. Setup a new Notification Service by creating a new java file and paste the code below in it
    • This allows you to present a notification to your user when a new notification arrives and will automatically sync new fcm tokens to Courier token management
// Your project import

import android.annotation.SuppressLint;
import androidx.annotation.NonNull;
import com.courier.android.notifications.RemoteMessageExtensionsKt;
import com.courier.android.service.CourierService;
import com.google.firebase.messaging.RemoteMessage;

// This is safe. `CourierService` will automatically handle token refreshes.
@SuppressLint("MissingFirebaseInstanceTokenRefresh")
public class YourExampleService extends CourierService {

    @Override
    public void showNotification(@NonNull RemoteMessage message) {
        super.showNotification(message);

        // TODO: This is where you will customize the notification that is shown to your users
        // The function below is used to get started quickly.
        // You likely do not want to use `message.presentNotification(...)`
        // For React Native, you likely do not want to change RemoteMessageExtensionsKt.presentNotification.handlingClass
        // More information on how to customize an Android notification here:
        // https://developer.android.com/develop/ui/views/notifications/build-notification

        RemoteMessageExtensionsKt.presentNotification(
                message,
                this,
                MainActivity.class,
                android.R.drawable.ic_dialog_info,
                "Notification Service"
        );

    }

}
  1. Add the Notification Service entry in your AndroidManifest.xml file
<manifest>
    <application>

        <activity>
            ..
        </activity>

        // Add this 👇
        <service
            android:name=".YourExampleService"
            android:exported="false">
            <intent-filter>
                <action android:name="com.google.firebase.MESSAGING_EVENT" />
            </intent-filter>
        </service>
        // Add this 👆

        ..

    </application>
</manifest>

Support Notifications

// Support the type of notifications you want to show on iOS
Courier.setIOSForegroundPresentationOptions({
  options: 'sound' | 'badge' | 'list' | 'banner'
});

// Request / Get Notification Permissions
final currentPermissionStatus = await Courier.getNotificationPermissionStatus();
final requestPermissionStatus = await Courier.requestNotificationPermission();

// Handle push events
const pushListener = Courier.shared.addPushListener(
  onPushClicked: (push) => {
    console.log(push);
  },
  onPushDelivered: (push) => {
    console.log(push);
  },
);

// Remove the listener where makes sense to you
pushListener.remove();

// Tokens
await Courier.shared.setToken({ key: "...", token: "..." });
await Courier.shared.getToken({ key: "..." });
const tokens = await Courier.shared.getAllTokens();

Send a Message

Provider Link
(APNS) - Apple Push Notification Service Testing Docs
(FCM) - Firebase Cloud Messaging Testing Docs

👋 TokenManagement APIs can be found here