1import { Notifications } from 'expo';
2
3import Constants from 'expo-constants';
4
5// In this test app we contact the Expo push service directly. You *never*
6// should do this in a real app. You should always store the push tokens on your
7// own server or use the local notification API if you want to notify this user.
8const PUSH_ENDPOINT = 'https://expo.io/--/api/v2/push/send';
9
10export default async function registerForPushNotificationsAsync() {
11  // this method assumes the user has already granted permission
12  // to receive remote notificartions.
13
14  // Get the token that uniquely identifies this device
15  const token = await Notifications.getExpoPushTokenAsync();
16
17  // Log it so we can easily copy it if we need to work with it
18  console.log(`Got this device's push token: ${token}`);
19
20  await Notifications.createCategoryAsync('welcome', [
21    {
22      actionId: 'tada',
23      buttonTitle: '��',
24      isDestructive: false,
25      isAuthenticationRequired: false,
26    },
27    {
28      actionId: 'heart_eyes',
29      buttonTitle: '��',
30      isDestructive: false,
31      isAuthenticationRequired: true,
32    },
33  ]);
34
35  // POST the token to the Expo push server
36  const response = await fetch(PUSH_ENDPOINT, {
37    method: 'POST',
38    headers: {
39      'Accept': 'application/json',
40      'Content-Type': 'application/json',
41    },
42    body: JSON.stringify([
43      {
44        to: token,
45        title: 'Welcome to Expo!',
46        body: 'Native Component List is registered for push notifications.',
47        data: { example: 'sample data' },
48        _category: `${Constants.manifest.id}:welcome`,
49      },
50    ]),
51  });
52
53  const result = await response.json();
54  if (result.errors) {
55    for (const error of result.errors) {
56      console.warn(`API error sending push notification:`, error);
57    }
58  }
59
60  const receipts = result.data;
61  if (receipts) {
62    const receipt = receipts[0];
63    if (receipt.status === 'error') {
64      if (receipt.details) {
65        console.warn(
66          `Expo push service reported an error sending a notification: ${
67            receipt.details.error
68          }`
69        );
70      }
71      if (receipt.__debug) {
72        console.warn(receipt.__debug);
73      }
74    }
75  }
76}
77