Trying to implement push notifications

This commit is contained in:
Gabriel Brown 2024-09-12 17:32:14 -05:00
parent 6407a23ee0
commit 868ad01c3f
6 changed files with 295 additions and 9 deletions

0
android/gradlew vendored Executable file → Normal file
View File

View File

@ -27,7 +27,6 @@ export default function HomeScreen() {
}
const user = JSON.parse(storedUser);
//const otherUserId = user.id === 1 ? 2 : 1;
const response = await axios.get(`${BASE_URL}/getMessage`, {
params: { apiKey: API_KEY, userId: user.id }

View File

@ -4,10 +4,16 @@ import { Stack } from 'expo-router';
import * as SplashScreen from 'expo-splash-screen';
import 'react-native-reanimated';
import { useColorScheme } from '@/hooks/useColorScheme';
import React, { useState, useEffect } from 'react';
import React, { useState, useEffect, useRef } from 'react';
import AsyncStorage from '@react-native-async-storage/async-storage';
import UserSelection from '@/components/UserSelection';
import { TouchableOpacity, Text } from 'react-native';
import { TouchableOpacity, Text, View } from 'react-native';
import * as Notifications from 'expo-notifications';
import * as Device from 'expo-device';
import Constants from 'expo-constants';
// Prevent the splash screen from auto-hiding before asset loading is complete.
SplashScreen.preventAutoHideAsync();
type User = {
id: number;
@ -15,16 +21,21 @@ type User = {
message: string;
};
// Prevent the splash screen from auto-hiding before asset loading is complete.
SplashScreen.preventAutoHideAsync();
export default function RootLayout() {
const API_KEY = process.env.EXPO_PUBLIC_API_KEY;
const BASE_URL = process.env.EXPO_PUBLIC_BASE_URL;
const colorScheme = useColorScheme();
const [loaded, error] = useFonts({
SpaceMono: require('../assets/fonts/SpaceMono-Regular.ttf'),
});
const [user, setUser] = useState<User | null>(null);
const [isLoading, setIsLoading] = useState(true);
// Push Notifications state
const [expoPushToken, setExpoPushToken] = useState<string | null>(null);
const notificationListener = useRef<Notifications.Subscription>();
const responseListener = useRef<Notifications.Subscription>();
useEffect(() => {
async function prepare() {
@ -54,8 +65,13 @@ export default function RootLayout() {
setUser(selectedUser);
try {
await AsyncStorage.setItem('@user', JSON.stringify(selectedUser));
// Store the Push Token to your server when the user is selected (optional)
if (expoPushToken) {
await savePushToken(selectedUser.id, expoPushToken); // Hypothetical function to send token to server
}
} catch (e) {
console.error('Failed to save user', e);
console.error('Failed to save user or push token', e);
}
};
@ -68,8 +84,66 @@ export default function RootLayout() {
}
};
/** --- PUSH NOTIFICATIONS LOGIC --- **/
useEffect(() => {
// Register for push notifications and set the push token
registerForPushNotificationsAsync().then(async (token) => {
if (token) {
setExpoPushToken(token);
// Upload push token to backend when successfully received
try {
const storedUser = await AsyncStorage.getItem('@user');
if (storedUser) {
const user = JSON.parse(storedUser);
// Send the push token to your Next.js API, along with the user's ID
await fetch(`${BASE_URL}/api/updatePushToken`, {
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify({
apiKey: API_KEY, // Use the API key stored in the environment
userId: user.id, // The logged-in user's ID
pushToken: token, // The Expo push token collected
}),
});
console.log('Push token successfully sent to backend');
} else {
console.log('No user found in AsyncStorage');
}
} catch (error) {
console.error('Failed to send push token to backend', error);
}
}
});
// Listener for received notifications while the app is running
notificationListener.current = Notifications.addNotificationReceivedListener(notification => {
console.log('Notification Received: ', notification);
});
// Listener for when the user interacts with a notification
responseListener.current = Notifications.addNotificationResponseReceivedListener(response => {
console.log('User interacted with notification: ', response);
});
// Clean up listeners when component unmounts
return () => {
if (notificationListener.current) {
Notifications.removeNotificationSubscription(notificationListener.current);
}
if (responseListener.current) {
Notifications.removeNotificationSubscription(responseListener.current);
}
};
}, []);
if (!loaded || isLoading) {
return null; // or a loading indicator
return null; // or a more elegant loading indicator
}
if (!user) {
@ -95,6 +169,56 @@ export default function RootLayout() {
/>
<Stack.Screen name="+not-found" />
</Stack>
{/* You can display the push token for debug purposes */}
{expoPushToken && (
<View style={{ padding: 10 }}>
<Text>Your Push Token: {expoPushToken}</Text>
</View>
)}
</ThemeProvider>
);
}
/** --- Helper functions for push notifications --- **/
// Function to get the push token and request permissions
async function registerForPushNotificationsAsync() {
let token;
// Ensure you're running on a physical device
if (Device.isDevice) {
const { status: existingStatus } = await Notifications.getPermissionsAsync();
let finalStatus = existingStatus;
// Ask user for permission if not granted already
if (existingStatus !== 'granted') {
const { status } = await Notifications.requestPermissionsAsync();
finalStatus = status;
}
if (finalStatus !== 'granted') {
console.log('Failed to get push notification token because permission not granted.');
return null;
}
try {
token = (await Notifications.getExpoPushTokenAsync()).data;
console.log('Expo Push Token:', token);
} catch (error) {
console.log('Failed to get Expo push token:', error);
return null;
}
} else {
console.log('Must use physical device for push notifications');
}
return token;
}
// (Optional) A function to store push tokens in your backend server
async function savePushToken(userId: number, expoPushToken: string) {
// You would need to implement this function to save the user's push token to your backend.
// For example, you could send a POST request to your Next.js API that stores expoPushToken
console.log('Saving push token for user:', userId, 'with token:', expoPushToken);
}

161
package-lock.json generated
View File

@ -16,9 +16,11 @@
"expo": "~51.0.28",
"expo-constants": "~16.0.2",
"expo-dev-client": "~4.0.26",
"expo-device": "~6.0.2",
"expo-font": "~12.0.9",
"expo-linear-gradient": "~13.0.2",
"expo-linking": "~6.3.1",
"expo-notifications": "~0.28.16",
"expo-router": "~3.5.23",
"expo-splash-screen": "~0.27.5",
"expo-status-bar": "~1.12.1",
@ -3578,6 +3580,12 @@
"@hapi/hoek": "^9.0.0"
}
},
"node_modules/@ide/backoff": {
"version": "1.0.0",
"resolved": "https://registry.npmjs.org/@ide/backoff/-/backoff-1.0.0.tgz",
"integrity": "sha512-F0YfUDjvT+Mtt/R4xdl2X0EYCHMMiJqNLdxHD++jDT5ydEFIyqbCHh51Qx2E211dgZprPKhV7sHmnXKpLuvc5g==",
"license": "MIT"
},
"node_modules/@isaacs/cliui": {
"version": "8.0.2",
"resolved": "https://registry.npmjs.org/@isaacs/cliui/-/cliui-8.0.2.tgz",
@ -7709,6 +7717,19 @@
"integrity": "sha512-BSHWgDSAiKs50o2Re8ppvp3seVHXSRM44cdSsT9FfNEUUZLOGWVCsiWaRPWM1Znn+mqZ1OfVZ3z3DWEzSp7hRA==",
"license": "MIT"
},
"node_modules/assert": {
"version": "2.1.0",
"resolved": "https://registry.npmjs.org/assert/-/assert-2.1.0.tgz",
"integrity": "sha512-eLHpSK/Y4nhMJ07gDaAzoX/XAKS8PSaojml3M0DM4JpV1LAi5JOJ/p6H/XWrl8L+DzVEvVCW1z3vWAaB9oTsQw==",
"license": "MIT",
"dependencies": {
"call-bind": "^1.0.2",
"is-nan": "^1.3.2",
"object-is": "^1.1.5",
"object.assign": "^4.1.4",
"util": "^0.12.5"
}
},
"node_modules/ast-types": {
"version": "0.15.2",
"resolved": "https://registry.npmjs.org/ast-types/-/ast-types-0.15.2.tgz",
@ -8070,6 +8091,12 @@
"@babel/core": "^7.0.0"
}
},
"node_modules/badgin": {
"version": "1.2.3",
"resolved": "https://registry.npmjs.org/badgin/-/badgin-1.2.3.tgz",
"integrity": "sha512-NQGA7LcfCpSzIbGRbkgjgdWkjy7HI+Th5VLxTJfW5EeaAf3fnS+xWQaQOCYiny+q6QSvxqoSO04vCx+4u++EJw==",
"license": "MIT"
},
"node_modules/balanced-match": {
"version": "1.0.2",
"resolved": "https://registry.npmjs.org/balanced-match/-/balanced-match-1.0.2.tgz",
@ -9957,6 +9984,15 @@
"expo": "bin/cli"
}
},
"node_modules/expo-application": {
"version": "5.9.1",
"resolved": "https://registry.npmjs.org/expo-application/-/expo-application-5.9.1.tgz",
"integrity": "sha512-uAfLBNZNahnDZLRU41ZFmNSKtetHUT9Ua557/q189ua0AWV7pQjoVAx49E4953feuvqc9swtU3ScZ/hN1XO/FQ==",
"license": "MIT",
"peerDependencies": {
"expo": "*"
}
},
"node_modules/expo-asset": {
"version": "10.0.10",
"resolved": "https://registry.npmjs.org/expo-asset/-/expo-asset-10.0.10.tgz",
@ -10078,6 +10114,44 @@
"node": ">=10"
}
},
"node_modules/expo-device": {
"version": "6.0.2",
"resolved": "https://registry.npmjs.org/expo-device/-/expo-device-6.0.2.tgz",
"integrity": "sha512-sCt91CuTmAuMXX4SlFOn4lIos2UIr8vb0jDstDDZXys6kErcj0uynC7bQAMreU5uRUTKMAl4MAMpKt9ufCXPBw==",
"license": "MIT",
"dependencies": {
"ua-parser-js": "^0.7.33"
},
"peerDependencies": {
"expo": "*"
}
},
"node_modules/expo-device/node_modules/ua-parser-js": {
"version": "0.7.39",
"resolved": "https://registry.npmjs.org/ua-parser-js/-/ua-parser-js-0.7.39.tgz",
"integrity": "sha512-IZ6acm6RhQHNibSt7+c09hhvsKy9WUr4DVbeq9U8o71qxyYtJpQeDxQnMrVqnIFMLcQjHO0I9wgfO2vIahht4w==",
"funding": [
{
"type": "opencollective",
"url": "https://opencollective.com/ua-parser-js"
},
{
"type": "paypal",
"url": "https://paypal.me/faisalman"
},
{
"type": "github",
"url": "https://github.com/sponsors/faisalman"
}
],
"license": "MIT",
"bin": {
"ua-parser-js": "script/cli.js"
},
"engines": {
"node": "*"
}
},
"node_modules/expo-file-system": {
"version": "17.0.1",
"resolved": "https://registry.npmjs.org/expo-file-system/-/expo-file-system-17.0.1.tgz",
@ -10279,6 +10353,61 @@
"invariant": "^2.2.4"
}
},
"node_modules/expo-notifications": {
"version": "0.28.16",
"resolved": "https://registry.npmjs.org/expo-notifications/-/expo-notifications-0.28.16.tgz",
"integrity": "sha512-sj4oDip+uFNmxieGHkfS2Usrwbw2jfOTfQ22a7z5tdSo/vD6jWMlCHOnJifqYLjPxyqf9SLTsQWO3bmk7MY2Yg==",
"license": "MIT",
"dependencies": {
"@expo/image-utils": "^0.5.0",
"@ide/backoff": "^1.0.0",
"abort-controller": "^3.0.0",
"assert": "^2.0.0",
"badgin": "^1.1.5",
"expo-application": "~5.9.0",
"expo-constants": "~16.0.0",
"fs-extra": "^9.1.0"
},
"peerDependencies": {
"expo": "*"
}
},
"node_modules/expo-notifications/node_modules/fs-extra": {
"version": "9.1.0",
"resolved": "https://registry.npmjs.org/fs-extra/-/fs-extra-9.1.0.tgz",
"integrity": "sha512-hcg3ZmepS30/7BSFqRvoo3DOMQu7IjqxO5nCDt+zM9XWjb33Wg7ziNT+Qvqbuc3+gWpzO02JubVyk2G4Zvo1OQ==",
"license": "MIT",
"dependencies": {
"at-least-node": "^1.0.0",
"graceful-fs": "^4.2.0",
"jsonfile": "^6.0.1",
"universalify": "^2.0.0"
},
"engines": {
"node": ">=10"
}
},
"node_modules/expo-notifications/node_modules/jsonfile": {
"version": "6.1.0",
"resolved": "https://registry.npmjs.org/jsonfile/-/jsonfile-6.1.0.tgz",
"integrity": "sha512-5dgndWOriYSm5cnYaJNhalLNDKOqFwyDB/rr1E9ZsGciGvKPs8R2xYGCacuf3z6K1YKDz182fd+fY3cn3pMqXQ==",
"license": "MIT",
"dependencies": {
"universalify": "^2.0.0"
},
"optionalDependencies": {
"graceful-fs": "^4.1.6"
}
},
"node_modules/expo-notifications/node_modules/universalify": {
"version": "2.0.1",
"resolved": "https://registry.npmjs.org/universalify/-/universalify-2.0.1.tgz",
"integrity": "sha512-gptHNQghINnc/vTGIk0SOFGFNXw7JVrlRUtConJRlvaw6DuX0wO5Jeko9sWrMBhh+PsYAZ7oXAiOnf/UKogyiw==",
"license": "MIT",
"engines": {
"node": ">= 10.0.0"
}
},
"node_modules/expo-router": {
"version": "3.5.23",
"resolved": "https://registry.npmjs.org/expo-router/-/expo-router-3.5.23.tgz",
@ -11848,6 +11977,22 @@
"node": ">=0.10.0"
}
},
"node_modules/is-nan": {
"version": "1.3.2",
"resolved": "https://registry.npmjs.org/is-nan/-/is-nan-1.3.2.tgz",
"integrity": "sha512-E+zBKpQ2t6MEo1VsonYmluk9NxGrbzpeeLC2xIViuO2EjU2xsXsBPwTr3Ykv9l08UYEVEdWeRZNouaZqF6RN0w==",
"license": "MIT",
"dependencies": {
"call-bind": "^1.0.0",
"define-properties": "^1.1.3"
},
"engines": {
"node": ">= 0.4"
},
"funding": {
"url": "https://github.com/sponsors/ljharb"
}
},
"node_modules/is-negative-zero": {
"version": "2.0.3",
"resolved": "https://registry.npmjs.org/is-negative-zero/-/is-negative-zero-2.0.3.tgz",
@ -16138,6 +16283,22 @@
"url": "https://github.com/sponsors/ljharb"
}
},
"node_modules/object-is": {
"version": "1.1.6",
"resolved": "https://registry.npmjs.org/object-is/-/object-is-1.1.6.tgz",
"integrity": "sha512-F8cZ+KfGlSGi09lJT7/Nd6KJZ9ygtvYC0/UYYLI9nmQKLMnydpB9yvbv9K1uSkEu7FU9vYPmVwLg328tX+ot3Q==",
"license": "MIT",
"dependencies": {
"call-bind": "^1.0.7",
"define-properties": "^1.2.1"
},
"engines": {
"node": ">= 0.4"
},
"funding": {
"url": "https://github.com/sponsors/ljharb"
}
},
"node_modules/object-keys": {
"version": "1.1.1",
"resolved": "https://registry.npmjs.org/object-keys/-/object-keys-1.1.1.tgz",

View File

@ -40,7 +40,9 @@
"react-native-screens": "3.31.1",
"react-native-vector-icons": "^10.1.0",
"react-native-web": "~0.19.10",
"expo-dev-client": "~4.0.26"
"expo-dev-client": "~4.0.26",
"expo-notifications": "~0.28.16",
"expo-device": "~6.0.2"
},
"devDependencies": {
"@babel/core": "^7.20.0",