Last active
November 23, 2020 23:50
-
-
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.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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 }; |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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