-
Notifications
You must be signed in to change notification settings - Fork 0
/
setUpNotifications.js
56 lines (48 loc) · 1.53 KB
/
setUpNotifications.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
import { Notifications } from 'expo'
import { Platform } from 'react-native'
import * as Permissions from 'expo-permissions'
import Constants from 'expo-constants'
// const PUSH_ENDPOINT = 'https://your-server.com/users/push-token'
function registerForPushNotificationsAsync() {
// eslint-disable-next-line no-async-promise-executor
return new Promise(async (resolve, reject) => {
if (!Constants.isDevice) reject(new Error('not a real device'))
try {
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') {
reject(new Error('no permission'))
}
const token = await Notifications.getExpoPushTokenAsync()
resolve(token)
} catch (e) {
reject(new Error('no permission'))
}
})
}
export function dismissNotifications() {
if (Platform.OS === 'ios') {
Notifications.setBadgeNumberAsync(0)
} else {
Notifications.dismissAllNotificationsAsync()
}
}
export function createAndroidNotificationChanel() {
if (Platform.OS === 'android') {
try {
Notifications.createChannelAndroidAsync('new-posts', {
name: 'New posts',
sound: true,
})
} catch (e) {
console.log('err createAndroidNotificationChanel', e)
}
}
}
export default registerForPushNotificationsAsync