React native local notifications

非 Y 不嫁゛ 提交于 2020-05-13 13:33:12

问题


I am new to React Native and need to implement a functionality where the app needs to send the user a notification every day at a certain time. The data to be shown for each day is stored in a json file on the client side and will not change. The notifications are on a schedule. Given that I was hoping there could be a way to just trigger a notification from the app itself.

Does anyone know of a way to achieve this without having to detach the app from expo? I can't use 'react-native-push-notification'without running react-native link and that requires me to detach the app. Is that right?

Is this possible?

Thanks :)


回答1:


You can do this with expo using the scheduleLocalNotificationAsync function (have a look at these docs for more details). Make sure you have permission to send notifications first. Note that if the notification triggers when the app is in the foreground you won't see a notification but you can still listen to this event.

i. Ask for permission

import { Permissions } from 'expo';

// ... somewhere before scheduling notifications ...
const { status } = await Permissions.getAsync(Permissions.NOTIFICATIONS);
if (status !== 'granted') {
  await Permissions.askAsync(Permissions.NOTIFICATIONS);
}

ii. Schedule the notification

import { Notifications } from 'expo';

const notification = {
  title: 'Hi there!',
  body: 'Tap me to open the app.',
  android: { sound: true }, // Make a sound on Android
  ios: { sound: true }, // Make a sound on iOS
};

const options = {
  time: Date.now() + 10000, // Schedule it in 10 seconds
  repeat: 'day', // Repeat it daily
};

// ... somewhere after requesting permission ...
const id = Notifications.scheduleLocalNotificationAsync(notification, options)

// If you want to react even when your app is still in the
// foreground, you can listen to the event like this:
Notifications.addListener(() => {
  console.log('triggered!');
});

iii. Cancel the scheduled notification

You can use the returned id of the scheduleLocalNotificationAsync function to cancel the notification.

import { Notifications } from 'expo';

// ... get the id of the scheduled notification ...

Notifications.cancelScheduledNotificationAsync(id)


来源:https://stackoverflow.com/questions/54872678/react-native-local-notifications

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!