Team-uMigrate / umigrate

Source code for the uMigrate project
13 stars 2 forks source link

Mobile: Push notifications #320

Closed deandrebaker closed 3 years ago

deandrebaker commented 3 years ago

Setup push notifications using expo-push-notifications

deandrebaker commented 3 years ago

Sample code in App.jsx ` import React, { useState, useEffect, useRef } from "react"; import { StatusBar } from "react-native"; import { AuthContextProvider } from "./src/contexts/AuthContext"; import { Provider as PaperProvider } from "react-native-paper"; import Constants from "expo-constants"; import as Notifications from "expo-notifications"; import as Permissions from "expo-permissions"; import AuthNavigator from "./src/navigators/AuthNavigator";

Notifications.setNotificationHandler({ handleNotification: async () => ({ shouldShowAlert: true, shouldPlaySound: true, shouldSetBadge: false, }), });

const App = () => { const [expoPushToken, setExpoPushToken] = useState(""); const [notification, setNotification] = useState(false); const notificationListener = useRef(); const responseListener = useRef();

useEffect(() => { registerForPushNotificationsAsync().then((token) => setExpoPushToken(token) ); notificationListener.current = Notifications.addNotificationReceivedListener( (notification) => { setNotification(notification); } ); responseListener.current = Notifications.addNotificationReceivedListener( (response) => { console.log(response); } ); return () => { Notifications.removeNotificationSubscription(notificationListener); Notifications.removeNotificationSubscription(responseListener); }; }, []);

return (

); };

export default App;

registerForPushNotificationsAsync = async () => { let token; if (Constants.isDevice) { const { status: existingStatus } = await Permissions.getAsync( Permissions.NOTIFICATIONS ); let finalStatus = existingStatus; if (existingStatus !== "granted") { const { status } = await Permissions.askAsync(Permissions.NOTIFICATIONS); finalStatus = status; } if (finalStatus !== "granted") { alert("Failed to get push token for push notification!"); return; } token = (await Notifications.getExpoPushTokenAsync()).data; console.log(token); } else { alert("Must use physical device for Push Notifications"); }

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

return token; };

`