یک راهنمای سریع برای فشار دادن اعلان ها با نمایش های نمایشی و Firebase

این روزها مجبور شدم اعلان های فشار را پیاده سازی کنم ، و از آنجا که من واقعاً دوست دارم نمایشگاه Direction در حال رفتن باشد ، تصمیم گرفتم بیشتر به اکوسیستم آن تکیه دهم ، بنابراین تصمیم گرفتم برای اجرای این ویژگی از نمایشگاه های نمایشگاه استفاده کنم. در کمال تعجب ، من هیچ راهنمای خوبی در مورد نحوه انجام آن پیدا نکردم. Expo راهنمایی در مورد چگونگی تنظیم آن از طریق خدمات اختصاصی خود دارد ، که من تصمیم گرفتم از آن استفاده نکنم تا از احساس قفل شدن پلتفرم جلوگیری کنم. شخصاً ، بزرگترین مزیت نمایشگاه ، اجرای دستی و مدیریت کد بومی به حداقل می رسد ، زیرا هرچه یک پروژه طولانی تر باشد ، پیگیری تغییرات در پرونده های مختلف برای کتابخانه های متعدد سخت تر می شود. بنابراین ما از نقاط قوت نمایشگاه با استفاده از نمایش های نمایشگاه برای تنظیم تقریباً تمام کد های بومی استفاده می کنیم و اعلان های فشار را در پیش زمینه انجام می دهیم در حالی که از پیام رسانی Firebase برای گوش دادن به رویدادهای اعلان ناشی از Firebase و رسیدگی به اعلان ها در پس زمینه استفاده خواهیم کرد.
npx expo install expo-notifications @react-native-firebase/app @react-native-firebase/messaging
در اینجا ما خدمات Google را پیکربندی می کنیم و اعلان ها را فشار می دهیم.
مسیر پرونده ها و DefaultChannel اولویت من است و قابل تغییر است.
اگر enableBackgroundRemoteNotifications
درست تنظیم شده است ، مجوزهای لازم برای رسیدگی به پیام های پس زمینه (هنگامی که برنامه باز است اما در تمرکز نیست یا برنامه بسته/کشته شده است) تنظیم می شود.
app.json
{
"expo": {
"ios": {
"googleServicesFile": "./assets/GoogleService-Info.plist"
}
"android": {
"googleServicesFile": "./assets/google-services.json"
}
}
"plugins": [
[
"expo-notifications",
{
"icon": "./assets/icon.png",
"color": "#002d2d",
"defaultChannel": "default",
"enableBackgroundRemoteNotifications": true
}
],
"@react-native-firebase/app",
"@react-native-firebase/messaging",
]
}
npx expo prebuild
می بینید که تمام نمادهای سازگار Android برای اعلان ها ایجاد شده اند و اجرای و مجوزهای بومی مورد نیاز تعیین شده است.
اما هیچ چیز کامل نیست. در این حالت ، اگر سعی در ساخت دارید ، احتمالاً خطایی خواهید داشت. هر دو نمایشنامه و پیام رسانی @React-Native-Firebase/پیام رسانی در تلاشند تا مقادیر اندرویدی را برای اعلان ها تنظیم کنند و ما باید با غلبه بر مقادیر com.google.firebase.messaging آن را به صورت دستی حل کنیم.
android/app/src/main/AndroidManifest.xml
-
+
-
+
-
+
اکنون می توانیم برنامه را بسازیم و اجرا کنیم.
npm run android
اکنون برنامه خود را پیکربندی می کنیم تا گوش دادن به پیام های ارسال شده از Firebase را شروع کنیم. هنگامی که در پس زمینه (برنامه در تمرکز یا بسته شدن نیست) ، سیستم عامل به طور خودکار اعلان ها را برای ما اداره می کند ، بنابراین ما باید مجوزهای لازم را اعطا کنیم تا به سیستم عامل اجازه دهد تا اعلان های فشار را نمایش دهد.
import { getMessaging } from "@react-native-firebase/messaging";
import { PermissionsAndroid } from "react-native";
// Get a Firebase Messaging service instance
const messaging = getMessaging();
//IOS Permission
await messaging.requestPermission();
//Android Permission
await PermissionsAndroid.request(
PermissionsAndroid.PERMISSIONS.POST_NOTIFICATIONS
);
// Subscribe to receive events from Firebase messaging service
await messaging.registerDeviceForRemoteMessages();
// Get device a FCM token for the device
const pushToken = await messaging.getToken();
// You probably would like save the token in a database
console.log("Firebase Token:", pushToken);
می توانید از طریق کنسول Firebase پیام ارسال کنید
اجرای> پیام رسانی> کمپین جدید> اعلان ها> ارسال پیام آزمایشی
ما در حال حاضر یک سیستم اطلاع رسانی اساسی در حال کار هستیم ، اما به عنوان یک انتخاب طراحی ، پیام رسانی Firebase به طور خودکار پیام ها را کنترل نمی کند وقتی برنامه در پیش زمینه قرار دارد (باز ، مورد استفاده قرار می گیرد) ، زیرا ما لزوماً نمی خواهیم اگر کاربر از برنامه استفاده کند ، اعلان فشار را نشان دهیم. در مورد استفاده من ، من می خواهم اعلان فشار را نشان دهم ، بنابراین می توانیم یک شنونده رویداد را ایجاد کنیم تا هنگام برنامه در پیش زمینه ، پیام ها را کنترل کند و از یادداشت های نمایشگاه استفاده کند تا سیستم عامل را برای نمایش اعلان فشار ایجاد کند.
import { getMessaging } from "@react-native-firebase/messaging";
import * as Notifications from "expo-notifications";
// Configure push notification behavior when app is in foreground
Notifications.setNotificationHandler({
handleNotification: async () => ({
shouldShowAlert: true,
shouldPlaySound: true,
shouldSetBadge: false,
shouldShowBanner: true,
shouldShowList: true,
}),
});
// Trigger notification at same moment
async function schedulePushNotification({
title = "New menage",
body = "You have a new message!",
data = {},
}) {
await Notifications.scheduleNotificationAsync({
content: {
title,
body,
data,
},
trigger: null,
});
}
// Get a Firebase Messaging service instance
const messaging = getMessaging();
useEffect(() => {
// Handle foreground messages and returns the cleanup function
const unsubscribeForeground = messaging.onMessage(async (remoteMessage) => {
schedulePushNotification({
title: remoteMessage?.notification?.title,
body: remoteMessage?.notification?.body,
data: remoteMessage?.data || {},
});
});
return () => {
// Clean the resources used for the listener
unsubscribeForeground();
};
}, []);
اگر می خواهید با کلیک بر روی آنها ، چگونگی تعامل اعلان ها با برنامه خود را کنترل کنید ، به عنوان مثال هدایت به یک صفحه خاص ، می توانید یک شنونده را برای این نوع رویداد نیز ایجاد کنید.
useEffect(() => {
// Handle app opening from a background messages and returns the cleanup function
const unsubscribeBackground = messaging.onNotificationOpenedApp(
// Handle navigation or app state changes
(remoteMessage) => {
console.log("Background message opened:", remoteMessage);
}
);
return () => {
// Clean the resources used for the listener
unsubscribeBackground();
};
}, []);
بنابراین ، برای اجرای کامل ، من یک قلاب را در یک فایل جداگانه ایجاد کردم تا کد را تمیز نگه دارم و با آن تماس بگیرم تا دستگاه را ثبت کرده و نشانه را در DB ذخیره کنم. من توکن را در قسمت عقب به همراه شناسه دستگاه ذخیره می کنم تا نشانه را هنگام تازه سازی یا هنگام نصب مجدد برنامه در همان دستگاه به روز کنم. از آنجا که داده ها به دلایل امنیتی در DB ذخیره می شوند ، من از یک توکن تحمل نیز به عنوان نوعی تأیید اعتبار استفاده می کنم.
import { getMessaging } from "@react-native-firebase/messaging";
import * as Notifications from "expo-notifications";
import { useEffect } from "react";
import { PermissionsAndroid, Platform } from "react-native";
import { getUniqueIdSync } from "react-native-device-info";
import { postPushNotification } from "../services/services";
// Configure push notification behavior when app is in foreground
Notifications.setNotificationHandler({
handleNotification: async () => ({
shouldShowAlert: true,
shouldPlaySound: true,
shouldSetBadge: false,
shouldShowBanner: true,
shouldShowList: true,
}),
});
// Trigger notification
async function schedulePushNotification({
title = "Nova mensagem",
body = "Você tem uma nova mensagem!",
data = {},
}) {
await Notifications.scheduleNotificationAsync({
content: {
title,
body,
data,
},
trigger: null,
});
}
// Configure push notification
export function useConfigPushNotification() {
// Firebase messaging service instance
const messaging = getMessaging();
const deviceId = getUniqueIdSync();
const platform = Platform.OS;
/**
* Handle permissions, register device in Firebase and save token in back end
* @param {string} bearerToken
*/
async function register(bearerToken) {
// IOS permission
await messaging.requestPermission();
// Android permission
await PermissionsAndroid.request(
PermissionsAndroid.PERMISSIONS.POST_NOTIFICATIONS
);
// Register device
await messaging.registerDeviceForRemoteMessages();
const pushToken = await messaging.getToken();
// Save token in back end
try {
await postPushNotification(bearerToken, platform, pushToken, deviceId);
} catch (err) {
console.log(err?.response);
}
}
useEffect(() => {
// Handle foreground messages and returns the cleanup function
const unsubscribeForeground = messaging.onMessage(async (remoteMessage) => {
schedulePushNotification({
title: remoteMessage?.notification?.title,
body: remoteMessage?.notification?.body,
data: remoteMessage?.data || {},
});
});
// Handle app opening from a background messages and returns the cleanup function
const unsubscribeBackground = messaging.onNotificationOpenedApp(
// Background message pop up is handled automatically
// Handle navigation or app state changes
(remoteMessage) => {
console.log("Background message opened:", remoteMessage);
}
);
return () => {
unsubscribeForeground();
unsubscribeBackground();
};
}, []);
return { register };
}
و در آخر ، برای رسیدگی به تنظیمات ، با قلاب تماس بگیرید.
const { register } = useConfigPushNotification();
// Config Push Notifications
try {
await register("bearer_token");
} catch (err) {
console.log(err);
}
امیدوارم این راهنما به شما کمک کند (و خود آینده من) اعلان های فشار را با استفاده از نمایشگاه و Firebase تنظیم کنید!
به من اطلاع دهید که آیا سوالی دارید یا چیزی وجود دارد که می تواند بهبود یابد.