expo のプロジェクトでローカル通知を行う

必要なライブラリをインストールします。

コピーしました!

shell
npx expo install expo-notifications

通知の許可を得る

以下のフックをプロジェクトのルートで読み込みます。

コピーしました!

useNotificationRequest.ts
import { useEffect } from 'react';
import { requestPermissionsAsync } from 'expo-notifications';

export const useNotificationRequest = () => {
  useEffect(() => {
    requestPermissionsAsync().then(({ status }) => {});
  }, []);
};

通知の設定

通知を設定する関数です。

コピーしました!

setNotification.ts
import {
  type NotificationContentInput,
  type NotificationTriggerInput,
  scheduleNotificationAsync,
  setNotificationHandler,
} from 'expo-notifications';

export const setNotification = async (
  content: NotificationContentInput,
  trigger: NotificationTriggerInput
): Promise<string> => {
  setNotificationHandler({
    handleNotification: async () => ({
      shouldShowAlert: true,
      shouldPlaySound: true,
      shouldSetBadge: true,
    }),
  });
  return await scheduleNotificationAsync({
    content,
    trigger,
  });
};

上の通知を設定する関数を使って、「24時間後に通知する」関数は以下のとおりです。

コピーしました!

setTomorrowsNotification.ts
import { type NotificationContentInput, type TimeIntervalTriggerInput } from 'expo-notifications';
import { i18n } from '@/functions/i18n/i18n';
import { setNotification } from '@/functions/notifications/setNotification';

export const setTomorrowsNotification = async () => {
  const content: NotificationContentInput = {
    title: i18n.t('notifications.title'),
    body: i18n.t('notifications.body'),
  };

  const trigger: TimeIntervalTriggerInput = {
    seconds: 24 * 60 * 60, // 24時間後 (24時間 * 60分 * 60秒)
    repeats: true,
  };

  await setNotification(content, trigger);
};

通知をすべて削除する

通知を削除する関数は以下の通りです。

コピーしました!

clearAllNotifications.ts
import { cancelAllScheduledNotificationsAsync, setNotificationHandler } from 'expo-notifications';

export const clearAllNotifications = async () => {
  setNotificationHandler({
    handleNotification: async () => ({
      shouldShowAlert: false,
      shouldPlaySound: false,
      shouldSetBadge: false,
    }),
  });

  // 通知を全て削除する
  await cancelAllScheduledNotificationsAsync();
};