| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687 |
- // app/hooks/usePushNotifications.ts
- import { useEffect, useState, useRef } from 'react';
- import * as Notifications from 'expo-notifications';
- import * as Device from 'expo-device';
- import Constants from 'expo-constants';
- import { Platform } from 'react-native';
- import { useTranslation } from '../../util/hooks/useTranslation';
- export interface PushNotificationState {
- notification?: Notifications.Notification;
- expoPushToken?: Notifications.ExpoPushToken;
- }
- export const usePushNotifications = (): PushNotificationState => {
- const [expoPushToken, setExpoPushToken] = useState<Notifications.ExpoPushToken | undefined>();
- const [notification, setNotification] = useState<Notifications.Notification | undefined>();
- const { t } = useTranslation();
- const notificationListener = useRef<Notifications.Subscription | undefined>(undefined);
- const responseListener = useRef<Notifications.Subscription | undefined>(undefined);
- useEffect(() => {
- Notifications.setNotificationHandler({
- handleNotification: async () => ({
- shouldPlaySound: true,
- shouldShowAlert: true,
- shouldSetBadge: true,
- vibrate: true,
- shouldShowWhenInForeground: true
- } as any)
- });
- registerForPushNotificationAsync(t).then((token) => {
- setExpoPushToken(token);
- });
- notificationListener.current = Notifications.addNotificationReceivedListener((notification) => {
- setNotification(notification);
- });
- responseListener.current = Notifications.addNotificationResponseReceivedListener((response) => {
- });
- return () => {
- notificationListener.current?.remove()
- responseListener.current?.remove()
- };
- }, []);
- return {
- expoPushToken,
- notification
- };
- };
- async function registerForPushNotificationAsync(t: Function) {
- let token;
- // Check if the device is a physical device, because this only works for physical devices not simulators
- if (Device.isDevice) {
- const { status: existingStatus } = await Notifications.getPermissionsAsync();
- let finalStatus = existingStatus;
- if (existingStatus !== 'granted') {
- const { status } = await Notifications.requestPermissionsAsync();
- finalStatus = status;
- }
- if (finalStatus !== 'granted') {
- alert(t('notifications.permission_required'));
- return;
- }
- //if we have permission, then get the token
- token = await Notifications.getExpoPushTokenAsync({
- projectId: Constants.expoConfig?.extra?.eas?.projectId
- });
- if (Platform.OS === 'android') {
- Notifications.setNotificationChannelAsync('default', {
- name: 'default',
- importance: Notifications.AndroidImportance.MAX,
- vibrationPattern: [0, 250, 250, 250],
- lightColor: '#FF231F7C'
- });
- }
- return token;
- } else {
- }
- }
|