Push Notifications - peophins-plasmas/pawsome-app GitHub Wiki
Expo Push Notifications for tasks
Push notifications are sent when a task's due date and due time are up. We use Expo push notifications for this.
Installations
Get started with npm install expo-notifications
Imports
Be sure to import the following:
import * as Notifications from "expo-notifications";
import Constants from "expo-constants";
Register for Push Notifications
Notifications can only be sent to physical devices so first check if app is being accessed from a device with Constants.isDevice
. This means we cannot test on a simulator. We check notification permissions. If permission is not granted, we request permission. If permission is still not granted, an alert is sent that a push token could not be obtained. When permission is granted, the token is obtained. In order to store this, create token state and set state to token and/or update the user with a token field on the database. See code below:
const registerForPushNotificationsAsync = async () => { if (Constants.isDevice) { const { status: existingStatus, } = await Notifications.getPermissionsAsync(); let finalStatus = existingStatus; if (existingStatus !== "granted") { const { status } = await Notifications.requestPermissionsAsync(); finalStatus = status; } if (finalStatus !== "granted") { alert("Failed to get push token for push notification!"); return; } try { const token = (await Notifications.getExpoPushTokenAsync()).data; setPushToken(token); } catch (error) { console.log(error); } } else { alert("Must use physical device for Push Notifications"); } };
Call the function in a useEffect(). In here, update the user's token field on the database. In this case, the variable is set as a string on Firestore so the token must be set as a string when updating the user's token field.
useEffect(() => { registerForPushNotificationsAsync() .then((token) => { if (user) { usersRef .doc(user.id) .update({ pushToken:
${pushToken} }) .then(() => { console.log(
Updated ${user.firstName} with push token.); }); } }) .catch((err) => console.log(err)); }, []); console.log("push token outside of useEffect", pushToken);
Testing Notifications
Expo has a notifications testing tool. An expo push token is required to test notifications to a specific device.