FCM android push

This commit is contained in:
Vincent (Wen Yu) Ge
2024-02-19 16:16:02 -05:00
parent 5a6af3c7bb
commit aa4cfd64f3
3 changed files with 223 additions and 11 deletions

View File

@@ -207,3 +207,20 @@ Available sizes are `s`, `m`, `l` and `xl`. Default: `s`.
{% only_dark %}I am only shown in Dark Theme{% /only_dark %} {% only_dark %}I am only shown in Dark Theme{% /only_dark %}
{% only_light %}I am only shown in Light Theme{% /only_light %} {% only_light %}I am only shown in Light Theme{% /only_light %}
``` ```
#### Cards
{% cards %}
{% cards_item href="/docs/quick-starts/react" title="React" %}
Get started with Appwrite and React
{% /cards_item %}
{% cards_item href="/docs/quick-starts/vue" title="Vue.js" %}
Get started with Appwrite and Vue.js
{% /cards_item %}
{% cards_item href="/docs/quick-starts/nuxt" title="Nuxt" %}
Get started with Appwrite and Nuxt
{% /cards_item %}
{% cards_item href="/docs/quick-starts/sveltekit" title="SvelteKit" %}
Get started with Appwrite and SvelteKit
{% /cards_item %}
{% /cards %}

View File

@@ -51,19 +51,9 @@ After adding the following details, click **Save and continue** to enable the pr
{% section #configure-app step=3 title="Configure app" %} {% section #configure-app step=3 title="Configure app" %}
Some additional configuration is required to enable push notifications in your mobile app. Some additional configuration is required to enable push notifications in your mobile app.
{% tabs %} {% tabs %}
{% tabsitem #fcm-ios title="iOS with FCM" %}
1. In your Firebase console, navigate to **Settings** > **General** > **Your apps** > add an **iOS** app.
1. Register and download your `google-services.json` config file.
1. Head to **Apple Developer Member Center** > **Program resources** > **Certificates, Identifiers & Profiles** > **Keys**. The key needs **Apple Push Notification Service** enabled.
1. Create a new key, note down the key ID and download your key.
1. In Firebase console, go to *Settings** > **Cloud Messaging** > **APNs authentication key** > click **Upload**. Upload your key here.
1. Add push notification capability to your app by clicking your root-level app in XCode > **Signing & Capabilities** > {% icon icon="plus" size="m" /%} Capabilities > Search for **Push Notifications**.
1. If using SwiftUI, disable swizzling by setting `FirebaseAppDelegateProxyEnabled` to `NO` in your `Info.plist`.
{% /tabsitem %}
{% tabsitem #fcm-android title="Android with FCM" %} {% tabsitem #fcm-android title="Android with FCM" %}
1. Install the `com.google.firebase:firebase-messaging` Firebase SDK.
1. In your Firebase console, navigate to **Settings** > **General** > **Your apps** > add an **Android** app. 1. In your Firebase console, navigate to **Settings** > **General** > **Your apps** > add an **Android** app.
1. Register and download your `google-services.json` config file. 1. Register and download your `google-services.json` config file.
1. Add `google-services.json` at the root of your project. 1. Add `google-services.json` at the root of your project.
@@ -78,6 +68,15 @@ Some additional configuration is required to enable push notifications in your m
</service> </service>
``` ```
{% /tabsitem %} {% /tabsitem %}
{% tabsitem #fcm-ios title="iOS with FCM" %}
1. In your Firebase console, navigate to **Settings** > **General** > **Your apps** > add an **iOS** app.
1. Register and download your `google-services.json` config file.
1. Head to **Apple Developer Member Center** > **Program resources** > **Certificates, Identifiers & Profiles** > **Keys**. The key needs **Apple Push Notification Service** enabled.
1. Create a new key, note down the key ID and download your key.
1. In Firebase console, go to *Settings** > **Cloud Messaging** > **APNs authentication key** > click **Upload**. Upload your key here.
1. Add push notification capability to your app by clicking your root-level app in XCode > **Signing & Capabilities** > {% icon icon="plus" size="m" /%} Capabilities > Search for **Push Notifications**.
1. If using SwiftUI, disable swizzling by setting `FirebaseAppDelegateProxyEnabled` to `NO` in your `Info.plist`.
{% /tabsitem %}
{% /tabs %} {% /tabs %}
{% /section %} {% /section %}

View File

@@ -4,4 +4,200 @@ title: Send push notification
description: Send push notification to your users using Appwrite Messaging. description: Send push notification to your users using Appwrite Messaging.
--- ---
You can send, schedule, and manage push notifications to your apps using Appwrite Messaging.
Push notifications can be used to deliver new message notifications, app updates, promotional offers,
and other messages straight to your user's devices.
{% section #add-provider step=1 title="Add provider" %}
Push notifications must be sent through third-party providers, like Apple Push Notification service and Firebase Cloud Messaging.
The push notification APIs for Apple and Android devices can only be accessed through these services.
You must configure these services before you can send your first push notification.
{% cards %}
{% cards_item href="/docs/products/messaging/apns" title="APNS" icon="icon-apple" %}
Configure APNs for push notification to Apple devices.
{% /cards_item %}
{% cards_item href="/docs/products/messaging/fcm" title="FCM" icon="icon-firebase" %}
Configure FCM for push notification to Android and Apple devices.
{% /cards_item %}
{% /cards %}
{% /section %}
{% section #add-targets step=2 title="Add targets" %}
Before sending your first push notification, your application must register itself for push notification,
then provide the device token to Appwrite.
{% tabs %}
{% tabsitem #apple-apns title="Apple with APNs" %}
{% /tabsitem %}
{% tabsitem #android-fcm title="Android with FCM" %}
Before you can send push notifications using FCM, make sure you'd followed the steps to
[Add Firebase to your Android project](https://firebase.google.com/docs/android/setup).
After adding Firebase to your Android project and adding the `google-services.json` to your project,
initialize Firebase in your main activity and fetch the FCM registration token.
```kotlin
class MainActivity : AppCompatActivity() {
override fun onCreate() {
// ... other logic
// Initialize Firebase
FirebaseApp.initializeApp(this)
// Set the FCM token
FirebaseMessaging.getInstance().token.addOnCompleteListener(OnCompleteListener { task ->
if (!task.isSuccessful) {
Log.w(TAG, "Fetching FCM registration token failed", task.exception)
return@OnCompleteListener
}
// Get new FCM registration token and save it in prefs to be used later.
val token = task.result
val prefs = getSharedPreferences("example", MODE_PRIVATE)
prefs.edit().putString("fcmToken", token).apply()
})
}
}
```
Appwrite's push targets are associated with accounts.
Typically, you would create a push target when the user logs in.
For example, when the user logs in with email and password, your app
can register itself as a target after handling the login.
```kotlin
fun onLogin(
email: String,
password: String,
token: String?,
) {
viewModelScope.launch {
try {
// Log in the user
val session = account.createEmailPasswordSession(
email,
password
)
// If a token exists, register a push target with Appwrite.
if (token != null) {
val target = account.createPushTarget(ID.unique(), token)
_target.postValue(Event(target))
}
_response.postValue(Event(session.toJson()))
} catch (e: AppwriteException) {
_error.postValue(Event(e))
}
}
}
```
The FCM token that we defined in `sharedPreferenes` will be passed into the `onLogin` handler
to create the push target.
```kotlin
binding.login.setOnClickListener{
viewModel.onLogin(
binding.email.text.toString(),
binding.password.text.toString(),
context
?.getSharedPreferences("example", Context.MODE_PRIVATE)
?.getString("fcmToken", null) ?: null
)
}
```
Your app also requires permissions to be able to receive push notifications.
First, add `POST_NOTIFICATIONS` to your `AndroidManifest.xml`.
```xml
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="YOUR_PACKAGE">
<uses-permission android:name="android.permission.POST_NOTIFICATIONS"/>
<!-- ... rest of your manifest -->
```
Then, request permissions to display push notifications in your app.
Appwrite provides a utility to help request permissions.
```kotlin
OS.requestPermission(
this, // Context
Manifest.permission.POST_NOTIFICATIONS, // Permission requested
onGranted = {
println("Permission granted") // When permission is granted
},
onDenied = {
println("Permission denied") // When permission is denied
},
onShowRationale = {
println("Should show rationale") // Explain why this permission is needed.
}
)
```
Lastly, because FCM push tokens can change, we need to add a service to handle FCM token
refreshes and update the target with Appwrite Messaging.
Create a new service that extends `FirebaseMessagingService` which handles the event where
the FCM token is updated.
```kotlin
class MessagingService : FirebaseMessagingService() {
companion object {
var account: Account? = null
}
// This is called when FCM token is updated.
override fun onNewToken(token: String) {
super.onNewToken(token)
val prefs = getSharedPreferences("example", MODE_PRIVATE)
prefs.edit().putString("fcmToken", token).apply()
if (account == null) {
return
}
val targetId = prefs.getString("targetId", null)
runBlocking {
if (targetId == null) {
val target = account!!.createPushTarget(ID.unique(), token)
prefs.edit().putString("targetId", target.id).apply()
} else {
account!!.updatePushTarget(targetId, token)
}
}
}
}
```
In your `AndroidManifest.xml`, register this new service.
```xml
<service android:name="io.appwrite.NotificationHandler" android:exported="false">
<intent-filter>
<action android:name="com.google.firebase.MESSAGING_EVENT" />
</intent-filter>
</service>
```
{% /tabsitem %}
{% /tabs %}
{% /section %}
{% section #request-permissions step=3 title="Request permissions" %}
Your app must ask for permission to receive push notification from the user.
Appwrite provides an `OS` class to help simplify the process to handle permissions.
{% /section %}