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