upd: push notifikasi
Deskripsi: - blm selesai No Issues
This commit is contained in:
78
lib/useNotification.ts
Normal file
78
lib/useNotification.ts
Normal file
@@ -0,0 +1,78 @@
|
||||
import firebase from '@react-native-firebase/app';
|
||||
import messaging from '@react-native-firebase/messaging';
|
||||
import { useEffect } from 'react';
|
||||
import { PermissionsAndroid } from 'react-native';
|
||||
|
||||
// Your Firebase project configuration
|
||||
const RNfirebaseConfig = {
|
||||
apiKey: "AIzaSyB2hbsW91J3oRQx4_jgrCCNY0tNt5-21e8",
|
||||
authDomain: "googleapis.com",
|
||||
projectId: "mobile-darmasaba",
|
||||
storageBucket: "mobile-darmasaba.appspot.com",
|
||||
messagingSenderId: "867439221179",
|
||||
appId: "1:867439221179:android:4509f77478c8dce99b0c9e",
|
||||
databaseURL: "https://mobile-darmasaba-default-rtdb.asia-southeast1.firebasedatabase.app/"
|
||||
};
|
||||
|
||||
let initialized = false;
|
||||
|
||||
const initializeFirebase = async () => {
|
||||
if (initialized) return;
|
||||
|
||||
try {
|
||||
if(!firebase.apps.length){
|
||||
firebase.initializeApp(RNfirebaseConfig)
|
||||
}
|
||||
|
||||
// Set auto initialization and background message handler
|
||||
messaging().setAutoInitEnabled(true);
|
||||
messaging().setBackgroundMessageHandler(async remoteMessage => {
|
||||
console.log('Message handled in the background!', remoteMessage);
|
||||
});
|
||||
} catch (error) {
|
||||
console.error('Failed to initialize Firebase:', error);
|
||||
throw error;
|
||||
}
|
||||
};
|
||||
|
||||
const requestPermission = async () => {
|
||||
try {
|
||||
const granted = await PermissionsAndroid.request(
|
||||
PermissionsAndroid.PERMISSIONS.POST_NOTIFICATIONS
|
||||
);
|
||||
if (granted === PermissionsAndroid.RESULTS.GRANTED) {
|
||||
console.log('Notification permission granted');
|
||||
} else {
|
||||
console.log('Notification permission denied');
|
||||
}
|
||||
} catch (err) {
|
||||
console.warn('Error requesting notification permissions:', err);
|
||||
}
|
||||
};
|
||||
|
||||
const getToken = async () => {
|
||||
try {
|
||||
const token = await messaging().getToken();
|
||||
console.log('Token:', token);
|
||||
return token;
|
||||
} catch (error) {
|
||||
console.error("Error getting token:", error);
|
||||
throw error;
|
||||
}
|
||||
};
|
||||
|
||||
export const useNotification = () => {
|
||||
useEffect(() => {
|
||||
const initializeAndSetup = async () => {
|
||||
try {
|
||||
await initializeFirebase();
|
||||
await requestPermission();
|
||||
await getToken();
|
||||
} catch (error) {
|
||||
console.error('Failed to setup notifications:', error);
|
||||
}
|
||||
};
|
||||
|
||||
initializeAndSetup();
|
||||
}, []);
|
||||
};
|
||||
Reference in New Issue
Block a user