Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Register a device for push notifications using expo-notifications and returning the Expo Push Token. Then send a push notification using the Expo Push Token.
import Constants from 'expo-constants';
import * as Notifications from 'expo-notifications';
import * as Permissions from 'expo-permissions';
const 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;
}
let res;
try {
res = await Notifications.getExpoPushTokenAsync();
token = res.data;
} catch (error) {
alert(JSON.stringify(error));
}
} 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;
};
export { registerForPushNotificationsAsync };
const { Expo } = require('expo-server-sdk');
module.exports = async (expoTokens, message) => {
const messages = [];
expoTokens.forEach(expoToken => {
messages.push({
to: expoToken,
sound: 'default',
body: message,
title: "Hello!"
});
});
const expo = new Expo();
const chunks = expo.chunkPushNotifications(messages);
for (const chunk of chunks) {
const ticketChunk = await expo.sendPushNotificationsAsync(chunk);
console.log(ticketChunk);
}
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.