boxons/components/useCases/timer/business/useNotifications.ts

92 lines
2.4 KiB
TypeScript

import { useEffect } from 'react';
import { PermissionsAndroid, Platform } from 'react-native';
import PushNotification, { Importance } from 'react-native-push-notification';
type ChannelInformationsType = {
channelId: string;
channelName: string;
channelDescription: string;
};
export function useNotification(
notificationId: string,
channelInformations: ChannelInformationsType
) {
useEffect(() => {
async function requestNotificationPermission() {
if (Platform.OS === 'android' && Platform.Version >= 33) {
const granted = await PermissionsAndroid.request(
PermissionsAndroid.PERMISSIONS.POST_NOTIFICATIONS
);
if (granted !== PermissionsAndroid.RESULTS.GRANTED) {
console.log('Permission de notification refusée');
}
}
}
requestNotificationPermission();
console.log('Initialisation des notifications');
PushNotification.configure({
onRegister: function (token) {
console.log('TOKEN:', token);
},
onNotification: function (notification) {
console.log('NOTIFICATION:', notification);
},
permissions: {
alert: true,
badge: true,
sound: true,
},
popInitialNotification: true,
requestPermissions: Platform.OS === 'ios',
});
if (Platform.OS === 'android') {
PushNotification.createChannel(
{
...channelInformations,
vibrate: true,
importance: Importance.HIGH,
},
(created) => console.log(`Canal créé avec succès : ${created}`)
);
}
PushNotification.localNotification({
channelId: 'timerChannel',
id: 'timer',
title: 'Hello',
message: 'My Notification Message',
playSound: false,
vibrate: false,
ongoing: true,
priority: 'high',
importance: 'high',
});
}, []);
function updateNotification(title: string, message: string) {
PushNotification.localNotification({
channelId: channelInformations.channelId,
id: parseInt(notificationId),
title,
message,
playSound: false,
vibrate: false,
ongoing: true,
priority: 'high',
importance: 'high',
onlyAlertOnce: true,
});
}
function cancelNotification() {
PushNotification.cancelLocalNotification(notificationId);
}
return { updateNotification, cancelNotification };
}