Skip to content

Instantly share code, notes, and snippets.

@magician11
Last active November 23, 2020 23:50
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save magician11/d5ce0b4a4f1c5ce0e9e6ef32df068efc to your computer and use it in GitHub Desktop.
Save magician11/d5ce0b4a4f1c5ce0e9e6ef32df068efc to your computer and use it in GitHub Desktop.
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