Files
workspace/code/app/app-rn/src/helpers/notification.ts
T
2026-07-19 21:57:40 +08:00

49 lines
1.5 KiB
TypeScript

import * as Notifications from "expo-notifications";
// -- 初始化配置 --
Notifications.setNotificationHandler({
handleNotification: async () => ({
shouldShowAlert: true,
shouldPlaySound: true,
shouldSetBadge: false,
}),
});
// -- 请求权限 --
export async function requestNotificationPermission(): Promise<boolean> {
const { status } = await Notifications.requestPermissionsAsync();
return status === "granted";
}
// -- 预定提醒通知 --
export async function scheduleTodoReminder(todoId: number, todoName: string, remindAt: string) {
if (!remindAt) return null;
const triggerDate = new Date(remindAt);
if (triggerDate <= new Date()) return null; // 时间已过,不预定
return Notifications.scheduleNotificationAsync({
content: {
title: "⏰ 待办提醒",
body: `「${todoName}」该处理了`,
data: { todoId, type: "todo_reminder" },
},
trigger: { type: Notifications.SchedulableTriggerInputTypes.DATE, date: triggerDate },
});
}
// -- 取消提醒通知 --
export async function cancelTodoReminder(identifier: string) {
await Notifications.cancelScheduledNotificationAsync(identifier);
}
// -- 取消某个todo的所有提醒 --
export async function cancelTodoReminders(todoId: number) {
const scheduled = await Notifications.getAllScheduledNotificationsAsync();
for (const n of scheduled) {
if ((n.content.data as any)?.todoId === todoId) {
await Notifications.cancelScheduledNotificationAsync(n.identifier);
}
}
}