Nelze vybrat více než 25 témat Téma musí začínat písmenem nebo číslem, může obsahovat pomlčky („-“) a může být dlouhé až 35 znaků.

PushNotification.tsx 4.1KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131
  1. import { useState, useEffect, useRef } from 'react';
  2. import { Text, View, Button, Platform } from 'react-native';
  3. import * as Device from 'expo-device';
  4. import * as Notifications from 'expo-notifications';
  5. import Constants from 'expo-constants';
  6. Notifications.setNotificationHandler({
  7. handleNotification: async () => ({
  8. shouldShowAlert: true,
  9. shouldPlaySound: true,
  10. shouldSetBadge: true,
  11. }),
  12. });
  13. // async function sendPushNotification(expoPushToken: string) {
  14. // const message = {
  15. // to: expoPushToken,
  16. // sound: 'default',
  17. // title: 'Original Title',
  18. // body: 'And here is the body!',
  19. // data: { someData: 'goes here' },
  20. // };
  21. // await fetch('https://exp.host/--/api/v2/push/send', {
  22. // method: 'POST',
  23. // headers: {
  24. // Accept: 'application/json',
  25. // 'Accept-encoding': 'gzip, deflate',
  26. // 'Content-Type': 'application/json',
  27. // },
  28. // body: JSON.stringify(message),
  29. // });
  30. // }
  31. function handleRegistrationError(errorMessage: string) {
  32. alert(errorMessage);
  33. throw new Error(errorMessage);
  34. }
  35. async function registerForPushNotificationsAsync() {
  36. if (Platform.OS === 'android') {
  37. Notifications.setNotificationChannelAsync('default', {
  38. name: 'default',
  39. importance: Notifications.AndroidImportance.MAX,
  40. vibrationPattern: [0, 250, 250, 250],
  41. lightColor: '#FF231F7C',
  42. });
  43. }
  44. if (Device.isDevice) {
  45. const { status: existingStatus } = await Notifications.getPermissionsAsync();
  46. let finalStatus = existingStatus;
  47. if (existingStatus !== 'granted') {
  48. const { status } = await Notifications.requestPermissionsAsync();
  49. finalStatus = status;
  50. }
  51. if (finalStatus !== 'granted') {
  52. handleRegistrationError('Permission not granted to get push token for push notification!');
  53. return;
  54. }
  55. const projectId = "1111cd70-7f71-4435-9db3-1c131ada169d";
  56. //Constants?.expoConfig?.extra?.eas?.projectId ?? Constants?.easConfig?.projectId;
  57. if (!projectId) {
  58. handleRegistrationError('Project ID not found');
  59. }
  60. try {
  61. const pushTokenString = (
  62. await Notifications.getExpoPushTokenAsync({
  63. projectId,
  64. })
  65. ).data;
  66. console.log(pushTokenString);
  67. return pushTokenString;
  68. } catch (e: unknown) {
  69. handleRegistrationError(`${e}`);
  70. }
  71. } else {
  72. handleRegistrationError('Must use physical device for push notifications');
  73. }
  74. }
  75. export default function PushNotification() {
  76. const [expoPushToken, setExpoPushToken] = useState('');
  77. const [notification, setNotification] = useState<Notifications.Notification | undefined>(
  78. undefined
  79. );
  80. const notificationListener = useRef<Notifications.EventSubscription>();
  81. const responseListener = useRef<Notifications.EventSubscription>();
  82. useEffect(() => {
  83. registerForPushNotificationsAsync()
  84. .then(token => setExpoPushToken(token ?? ''))
  85. .catch((error: any) => setExpoPushToken(`${error}`));
  86. notificationListener.current = Notifications.addNotificationReceivedListener(notification => {
  87. setNotification(notification);
  88. });
  89. responseListener.current = Notifications.addNotificationResponseReceivedListener(response => {
  90. console.log(response);
  91. });
  92. return () => {
  93. notificationListener.current &&
  94. Notifications.removeNotificationSubscription(notificationListener.current);
  95. responseListener.current &&
  96. Notifications.removeNotificationSubscription(responseListener.current);
  97. };
  98. }, []);
  99. return (
  100. <View style={{ flex: 1, alignItems: 'center', justifyContent: 'space-around' }}>
  101. <Text>Your Expo push token: {expoPushToken}</Text>
  102. <View style={{ alignItems: 'center', justifyContent: 'center' }}>
  103. <Text>Title: {notification && notification.request.content.title} </Text>
  104. <Text>Body: {notification && notification.request.content.body}</Text>
  105. <Text>Data: {notification && JSON.stringify(notification.request.content.data)}</Text>
  106. </View>
  107. {/* <Button
  108. title="Press to Send Notification"
  109. onPress={async () => {
  110. await sendPushNotification(expoPushToken);
  111. }}
  112. /> */}
  113. </View>
  114. );
  115. }