push-notifications.ts (1153B)
1 import Constants from 'expo-constants'; 2 import * as Notifications from 'expo-notifications'; 3 4 export const registerForPushNotificationsAsync = async (): Promise<void> => { 5 const { status: existingStatus } = await Notifications.getPermissionsAsync(); 6 7 // only ask if permissions have not already been determined, because 8 // iOS won't necessarily prompt the user a second time. 9 if (existingStatus !== 'granted') { 10 // Android remote notification permissions are granted during the app 11 // install, so this will only ask on iOS 12 await Notifications.requestPermissionsAsync(); 13 } 14 }; 15 16 export const getPushNotificationStatusAsync = async (): Promise< 17 string | undefined 18 > => { 19 let token; 20 if (Constants.isDevice) { 21 const { 22 status: existingStatus 23 } = await Notifications.getPermissionsAsync(); 24 let finalStatus = existingStatus; 25 if (existingStatus !== 'granted') { 26 const { status } = await Notifications.requestPermissionsAsync(); 27 finalStatus = status; 28 } 29 if (finalStatus !== 'granted') { 30 return; 31 } 32 token = (await Notifications.getExpoPushTokenAsync()).data; 33 } 34 35 return token; 36 };