Code Monkey home page Code Monkey logo

courier-flutter's Introduction

Courier Flutter Overview

Courier.shared.isDebugging = true;

final userId = await Courier.shared.userId;

await Courier.shared.signIn(
    accessToken: 'asdf...',
    userId: 'example_user_id',
);

await Courier.shared.signOut();

Courier.shared.iOSForegroundNotificationPresentationOptions = [
    iOSNotificationPresentationOption.banner,
    iOSNotificationPresentationOption.sound,
    iOSNotificationPresentationOption.list,
    iOSNotificationPresentationOption.badge,
];

final currentPermissionStatus = await Courier.shared.getNotificationPermissionStatus();
final requestPermissionStatus = await Courier.shared.requestNotificationPermission();

await Courier.shared.setFcmToken(token: 'asdf...');

final fcmToken = await Courier.shared.fcmToken;
final apnsToken = await Courier.shared.apnsToken;

Courier.shared.onPushNotificationDelivered = (push) {
    print(push);
};

Courier.shared.onPushNotificationClicked = (push) {
    print(push);
};

final messageId = await Courier.shared.sendPush(
    authKey: 'asdf...',
    userId: 'example_user_id',
    title: 'Hey! ๐Ÿ‘‹',
    body: 'Courier is awesome!!',
    isProduction: false,
    providers: [CourierProvider.apns, CourierProvider.fcm],
);

Requirements & Support

Operating System Min SDK Compile SDK Firebase Cloud Messaging Apple Push Notification Service Expo OneSignal Courier Inbox Courier Toast
iOS 13 โ€” โœ… โœ… โŒ โŒ โŒ โŒ
Android 21 33 โœ… โŒ โŒ โŒ โŒ โŒ

Most of this SDK depends on a Courier account: Create a Courier account here

Testing push notifications requires a physical device. Simulators will not work.

Installation

Link to Example App

  1. Install the package
  2. iOS Setup
  3. Android Setup
  4. Configure Push Provider
  5. Managing User State
  6. Testing Push Notifications

โ€ƒ

1. Install the package

Run the following command at your project's root directory:

flutter pub add courier_flutter

โ€ƒ

2. iOS Setup

If you don't need push notification support on iOS, you can skip this step.

flutter-ios-push-setup.mov
  1. Open your iOS project and increase the min SDK target to iOS 13.0+
  2. From your Flutter project's root directory, run: cd ios && pod update
  3. Change your AppDelegate to extend the CourierFlutterDelegate and add import courier_flutter to the top of your AppDelegate file
    • This automatically syncs APNS tokens to Courier
    • Allows the Flutter SDK to handle when push notifications are delivered and clicked
  4. Enable the "Push Notifications" capability

Add the Notification Service Extension (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.

flutter-ios-notification-service-setup.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"), select Courier_iOS as the Package, and click "Finish"
  6. Click "Cancel" on the next popup
    • You do NOT need to click "Activate" here. Your Notification Service Extension will still work just fine.
  7. Select Service Extension (i.e. "CourierService"), select general, change deployment sdk to min SDK target to iOS 13.0+
  8. Open your Podfile and add the following snippet to the end of your Podfile
    • This will link the Courier-iOS pod to your Notification Service Extension
target 'CourierService' do
  use_frameworks!
  pod 'Courier-iOS'
end
  1. From the root of your Flutter app, run: cd ios && pod install

โ€ƒ

3. Android Setup

If you don't need push notification support on Android, you can skip this step.

flutter-android-push-setup.mov
  1. Open Android project
  2. Add support for Jitpack to android/build.gradle
    • This is needed because the Courier Android SDK is hosted using Jitpack
    • Maven Central support will be coming later
allprojects {
    repositories {
        google()
        mavenCentral()
        maven { url 'https://jitpack.io' } // Add this line
    }
}
  1. Update your app/build.gradle to support the min and compile SDKs
    • minSdkVersion 21
    • compileSdkVersion 33
  2. Run Gradle sync
  3. Change your MainActivity to extend the CourierFlutterActivity
    • This allows Courier to handle when push notifications are delivered and clicked
  4. Setup a new Notification Service by creating a new file and pasting the code below in it
    • This allows you to present a notification to your user when a new notification arrives
import android.annotation.SuppressLint
import com.courier.android.notifications.presentNotification
import com.courier.android.service.CourierService
import com.google.firebase.messaging.RemoteMessage

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

    override fun showNotification(message: RemoteMessage) {
        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 Flutter, you likely do not want to change the handlingClass
        // More information on how to customize an Android notification here:
        // https://developer.android.com/develop/ui/views/notifications/build-notification

        message.presentNotification(
            context = this,
            handlingClass = MainActivity::class.java,
            icon = android.R.drawable.ic_dialog_info
        )

    }

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

        <activity>
            ..
        </activity>

        // Add this ๐Ÿ‘‡
        <service
            android:name=".YourNotificationService"
            android:exported="false">
            <intent-filter>
                <action android:name="com.google.firebase.MESSAGING_EVENT" />
            </intent-filter>
        </service>
        // Add this ๐Ÿ‘†

        ..

    </application>
</manifest>

โ€ƒ

4. Configure Push Provider

If you don't need push notification support, you can skip this step.

To get push notification to appear in your app, add support for the provider you would like to use:

โ€ƒ

5. Managing User State

Best user experience practice is to synchronize the current user's push notification tokens and the user's state. Courier does most of this for you automatically!

You can use a Courier Auth Key found here when developing.

When you are ready for production release, you should be using a JWT as the accessToken. Here is more info about Going to Production

Place these functions where you normally manage your user's state:

// Saves accessToken and userId to native level local storage
// This will persist between app sessions
await Courier.shared.signIn(
    accessToken: accessToken,
    userId: userId,
);

await Courier.shared.signOut();

If you followed the steps above:

  • APNS tokens on iOS will automatically be synced to Courier
  • FCM tokens on Android will automatically be synced to Courier

If you want FCM tokens to sync to Courier on iOS:

  1. Add the following Flutter packages to your project

  2. Add code to manually sync FCM tokens

final fcmToken = await FirebaseMessaging.instance.getToken();
if (fcmToken != null) {
    await Courier.shared.setFcmToken(token: fcmToken);
}

// Handle FCM token refreshes
FirebaseMessaging.instance.onTokenRefresh.listen((fcmToken) {
    Courier.shared.setFcmToken(token: fcmToken);
});

โ€ƒ

6. Testing Push Notifications

If you don't need push notification support, you can skip this step.

Courier allows you to send a push notification directly from the SDK to a user id. No tokens juggling or backend needed!

final notificationPermission = await Courier.shared.getNotificationPermissionStatus();
print(notificationPermission);

// Notification permissions must be `authorized` on iOS to receive pushes
final requestedNotificationPermission = await Courier.shared.requestNotificationPermission();
print(requestedNotificationPermission);

// This is how iOS will show the notification when the app is in the foreground
// Passing [] will not present anything
// `Courier.shared.onPushNotificationDelivered` will still get called
Courier.shared.iOSForegroundNotificationPresentationOptions = [
    iOSNotificationPresentationOption.banner,
    iOSNotificationPresentationOption.sound,
    iOSNotificationPresentationOption.list,
    iOSNotificationPresentationOption.badge,
];

// Will be called if the app is in the foreground and a push notification arrives
Courier.shared.onPushNotificationDelivered = (push) {
    ...
};

// Will be called when a user clicks a push notification
Courier.shared.onPushNotificationClicked = (push) {
    ...
};

// Sends a test push
final messageId = await Courier.shared.sendPush(
    authKey: 'a_courier_auth_key_that_should_only_be_used_for_testing',
    userId: 'example_user',
    title: 'Chirp Chrip!',
    body: 'Hello from Courier ๐Ÿฃ',
    isProduction: false, // This only affects APNS pushes. false == sandbox / true == production
    providers: [CourierProvider.apns, CourierProvider.fcm],
);

โ€ƒ

Going to Production

For security reasons, you should not keep your authKey (which looks like: pk_prod_ABCD...) in your production app. The authKey is safe to test with, but you will want to use an accessToken in production.

To create an accessToken, call this:

curl --request POST \
     --url https://api.courier.com/auth/issue-token \
     --header 'Accept: application/json' \
     --header 'Authorization: Bearer $YOUR_AUTH_KEY' \
     --header 'Content-Type: application/json' \
     --data
 '{
    "scope": "user_id:$YOUR_USER_ID write:user-tokens",
    "expires_in": "$YOUR_NUMBER days"
  }'

Or generate one here: Issue Courier Access Token

This request to issue a token should likely exist in a separate endpoint served on your backend.

โ€ƒ

Share feedback with Courier

We want to make this the best SDK for managing notifications! Have an idea or feedback about our SDKs? Here are some links to contact us:

courier-flutter's People

Contributors

mikemilla avatar fahadaminshovon avatar

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.