Advertisement
Guest User

Untitled

a guest
Jan 6th, 2023
205
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1.  //// App.js
  2.  
  3. const { permissions, schedulePushNotification } = useNotifications();
  4.  
  5.   return(
  6.     <>
  7.     <Button title="Enable notifications - onboarding screen only button" onPress={permissions} />
  8.     <Button title="Schedule notification" onPress={schedulePushNotification} />
  9.     </>
  10.   )
  11.  
  12.   /// useNotifications.js hook
  13.  
  14.   import { View, Text, Platform } from "react-native";
  15. import React, { useEffect, useState, useRef } from "react";
  16. import * as Notifications from "expo-notifications";
  17. import * as Device from "expo-device";
  18. // import { useNavigation } from "@react-navigation/native";
  19.  
  20. Notifications.setNotificationHandler({
  21.   handleNotification: async () => ({
  22.     shouldShowAlert: true,
  23.     shouldPlaySound: true,
  24.     shouldSetBadge: false,
  25.   }),
  26. });
  27.  
  28. export default function useNotifications() {
  29.   const [expoPushToken, setExpoPushToken] = useState("");
  30.   const [givenNotificationPerm, setGivenNotificationPerm] = useState(false);
  31.   const [notification, setNotification] = useState(false);
  32.   const notificationListener = useRef();
  33.   const responseListener = useRef();
  34.  
  35.   useEffect(() => {
  36.     // permissions(); - asks for permission
  37.     givenPermissions(); // checks if has permissions
  38.     getScheduled(); // get current notifications in pipeline
  39.  
  40.     notificationListener.current =
  41.       Notifications.addNotificationReceivedListener((notification) => {
  42.         setNotification(notification);
  43.         console.log("--- notification received ---");
  44.         // const show_time = notification?.request?.trigger?.dateComponents;
  45.         // console.log(show_time);
  46.         console.log(notification);
  47.         console.log("------");
  48.       });
  49.  
  50.     responseListener.current =
  51.       Notifications.addNotificationResponseReceivedListener((response) => {
  52.         console.log("--- notification tapped ---");
  53.         const screen = response?.notification?.request?.content?.data?.screen;
  54.         const show_time =
  55.           response?.notification?.request?.content?.data?.show_time; // temp
  56.         // navigation.navigate("Root", { screen: screen });
  57.         console.log("this showed: " + show_time);
  58.         console.log("------");
  59.       });
  60.  
  61.     return () => {
  62.       Notifications.removeNotificationSubscription(
  63.         notificationListener.current
  64.       );
  65.       Notifications.removeNotificationSubscription(responseListener.current);
  66.     };
  67.   }, []);
  68.  
  69.   async function permissions() {
  70.     registerForPushNotificationsAsync().then((token) =>
  71.       setExpoPushToken(token)
  72.     );
  73.   }
  74.  
  75.   async function getScheduled() {
  76.     console.log("getting schedfuled notifcation");
  77.  
  78.     const slay = await Notifications.getAllScheduledNotificationsAsync();
  79.     console.log("scheduled:");
  80.     console.log(slay);
  81.   }
  82.  
  83.   async function schedulePushNotification() {
  84.     console.log("reqested notifcation");
  85.     const randomSeconds = Math.floor(Math.random() * 20) + 1;
  86.  
  87.     const months = [
  88.       "January",
  89.       "February",
  90.       "March",
  91.       "April",
  92.       "May",
  93.       "June",
  94.       "July",
  95.     ];
  96.     const random = Math.floor(Math.random() * months.length);
  97.  
  98.     const trigger = await Notifications.getNextTriggerDateAsync({
  99.       second: randomSeconds,
  100.       repeats: true,
  101.     });
  102.     await Notifications.scheduleNotificationAsync({
  103.       content: {
  104.         title: "A test notif!",
  105.         body: `${months[random]} is random`,
  106.         data: { screen: "screenName", show_time: trigger.second },
  107.       },
  108.       trigger,
  109.     });
  110.     getScheduled();
  111.   }
  112.  
  113.   async function registerForPushNotificationsAsync() {
  114.     let token;
  115.  
  116.     if (Platform.OS === "android") {
  117.       await Notifications.setNotificationChannelAsync("default", {
  118.         name: "default",
  119.         importance: Notifications.AndroidImportance.MAX,
  120.         vibrationPattern: [0, 250, 250, 250],
  121.         lightColor: "#FF231F7C",
  122.       });
  123.     }
  124.  
  125.     if (Device.isDevice) {
  126.       const { status: existingStatus } =
  127.         await Notifications.getPermissionsAsync();
  128.       let finalStatus = existingStatus;
  129.       if (existingStatus !== "granted") {
  130.         const { status } = await Notifications.requestPermissionsAsync();
  131.         finalStatus = status;
  132.       }
  133.       if (finalStatus !== "granted") {
  134.         alert("Failed to get push token for push notification!");
  135.         return;
  136.       }
  137.       token = (await Notifications.getExpoPushTokenAsync()).data;
  138.       console.log(token);
  139.     } else {
  140.       alert("Must use physical device for Push Notifications");
  141.     }
  142.  
  143.     return token;
  144.   }
  145.  
  146.   async function givenPermissions() {
  147.     if (Device.isDevice) {
  148.       const { status: existingStatus } =
  149.         await Notifications.getPermissionsAsync();
  150.       if (existingStatus !== "granted") {
  151.         setGivenNotificationPerm(false);
  152.       }
  153.       setGivenNotificationPerm(true);
  154.     } else {
  155.       alert("Must use physical device for Push Notifications");
  156.     }
  157.   }
  158.  
  159.   return {
  160.     expoPushToken,
  161.     notification,
  162.     permissions,
  163.     schedulePushNotification,
  164.     givenNotificationPerm,
  165.   };
  166. }
  167.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement