Untitled

 avatar
unknown
plain_text
a month ago
4.8 kB
2
Indexable
import { useEffect, useRef } from 'react';
import * as Notifications from 'expo-notifications';
import { EventSubscription } from 'expo-modules-core';
import notificationService from '../services/notificationService';

export const useNotifications = () => {
  const notificationListener = useRef<EventSubscription>();
  const responseListener = useRef<EventSubscription>();

  useEffect(() => {
    // Register for push notifications
    notificationService.registerForPushNotifications();

    // Add notification listeners
    notificationListener.current = notificationService.addNotificationReceivedListener(
      notification => {
        console.log('Notification received:', notification);
      }
    );

    responseListener.current = notificationService.addNotificationResponseReceivedListener(
      response => {
        console.log('Notification response:', response);
      }
    );

    // Cleanup listeners on unmount
    return () => {
      if (notificationListener.current) {
        notificationListener.current.remove();
      }
      if (responseListener.current) {
        responseListener.current.remove();
      }
    };
  }, []);

  const sendTestNotification = async () => {
    await notificationService.scheduleLocalNotification(
      'Test Notification',
      'This is a test notification!',
      2 // Show after 2 seconds
    );
  };

  return {
    expoPushToken: notificationService.expoPushToken,
    sendTestNotification,
  };
};


-----


import * as Device from 'expo-device';
import * as Notifications from 'expo-notifications';
import { Platform } from 'react-native';
import { EventSubscription } from 'expo-modules-core';

// Configure how notifications should be presented when the app is in foreground
Notifications.setNotificationHandler({
  handleNotification: async () => ({
    shouldShowAlert: true,
    shouldPlaySound: true,
    shouldSetBadge: true,
  }),
});

export class NotificationService {
  private static instance: NotificationService;
  private _expoPushToken: string | undefined;

  private constructor() {}

  static getInstance(): NotificationService {
    if (!NotificationService.instance) {
      NotificationService.instance = new NotificationService();
    }
    return NotificationService.instance;
  }

  async registerForPushNotifications(): Promise<string | undefined> {
    if (!Device.isDevice) {
      console.log('Must use physical device for Push Notifications');
      return;
    }

    try {
      const { status: existingStatus } = await Notifications.getPermissionsAsync();
      let finalStatus = existingStatus;

      if (existingStatus !== 'granted') {
        const { status } = await Notifications.requestPermissionsAsync();
        finalStatus = status;
      }

      if (finalStatus !== 'granted') {
        console.log('Failed to get push token for push notification!');
        return;
      }

      // Get the token that uniquely identifies this device
      const expoPushToken = await Notifications.getExpoPushTokenAsync({
        projectId: 'mylottoappprojectid', // Your project ID from app.json
      });

      this._expoPushToken = expoPushToken.data;

      // Required for Android
      if (Platform.OS === 'android') {
        await Notifications.setNotificationChannelAsync('default', {
          name: 'default',
          importance: Notifications.AndroidImportance.MAX,
          vibrationPattern: [0, 250, 250, 250],
          lightColor: '#FF231F7C',
        });
      }

      return expoPushToken.data;
    } catch (error) {
      console.error('Error registering for push notifications:', error);
      return undefined;
    }
  }

  get expoPushToken(): string | undefined {
    return this._expoPushToken;
  }

  async scheduleLocalNotification(
    title: string,
    body: string,
    seconds: number = 1
  ): Promise<void> {
    await Notifications.scheduleNotificationAsync({
      content: {
        title,
        body,
      },
      trigger: null,
    });
  }

  addNotificationReceivedListener(
    callback: (notification: Notifications.Notification) => void
  ): EventSubscription {
    return Notifications.addNotificationReceivedListener(callback);
  }

  addNotificationResponseReceivedListener(
    callback: (response: Notifications.NotificationResponse) => void
  ): EventSubscription {
    return Notifications.addNotificationResponseReceivedListener(callback);
  }

  async dismissAllNotifications(): Promise<void> {
    await Notifications.dismissAllNotificationsAsync();
  }

  async getBadgeCount(): Promise<number> {
    return await Notifications.getBadgeCountAsync();
  }

  async setBadgeCount(count: number): Promise<void> {
    await Notifications.setBadgeCountAsync(count);
  }
}

export default NotificationService.getInstance();
Editor is loading...
Leave a Comment