react-native-push-notification 在第二天不重复本地日程通知

问题描述

我在未来一天设置了本地日程通知,通知在第一次工作但在第二天不起作用,当我调用 getScheduledLocalNotifications() 并且日期已经设置在未来时,通知仍然返回,我正在测试三星 s10e one ui 3.0

注意:通知在后台运行良好

我使用的是 RN 0.63.4 和 [email protected]

这里是要复现的代码

LocalPushController.js

import PushNotificationIOS from "@react-native-community/push-notification-ios";
import dayjs from "dayjs";
import PushNotification from "react-native-push-notification";
import { NOTIFICATION_CHANNELID } from "@env";
import { GET_NOTIS } from "../store/remiders/reminders.action";

export const PushNotificationInit = () => {
  PushNotification.configure({
    // (required) Called when a remote or local notification is opened or received
    onNotification: function (notification) {
      console.log("NOTIFICATION:",notification);
      console.log(dayjs(notification.firedate).format("HH:mm DD/MM/YYYY"));
      // console.log(
      //   new Date(notification.fireDate).getHours(),//   new Date(notification.fireDate).getMinutes()
      // );
      // process the notification

      // (required) Called when a remote is received or opened,or local notification is opened
      notification.finish(PushNotificationIOS.FetchResult.NoData);
    },popInitialNotification: true,requestPermissions: true,});

  PushNotification.createChannel(
    {
      channelId: NOTIFICATION_CHANNELID || "scheduleLocal",// (required)
      channelName: "Gywreb Reminder",// (required)
      channelDescription: "A channel to categorise your notifications",// (optional) default: undefined.
      soundName: "default",// (optional) See `soundName` parameter of `localNotification` function
      importance: 4,vibrate: true,// (optional) default: true. Creates the default vibration patten if true.
    },(created) => console.log(`createChannel returned '${created}'`) // (optional) callback returns whether the channel was created,false means it already existed.
  );
};

export const LocalScheduleNotification = (date,id,notiConfig) => {
  const { description,title,repeatType } = notiConfig;
  console.log(date);
  // console.log(notiConfig);

  PushNotification.localNotificationSchedule({
    id,channelId: NOTIFICATION_CHANNELID || "scheduleLocal",bigText: description,message: "Expand to see more details",vibration: 200,playSound: true,soundName: "default",date,repeatType,autoCancel: false,number: 10,allowWhileIdle: true,});
};

export const GetLocalScheduleNotifications = (dispatch) => {
  let notiList = [];
  PushNotification.getScheduledLocalNotifications((notis) => {
    notiList = [...notis];
    dispatch({ type: GET_NOTIS,payload: notis });
  });
  return notiList;
};

export const CancelLocalScheduleNotification = (id) => {
  PushNotification.cancelLocalNotifications({ id: "" + id });
};

ReminderEditScreen.js

import React,{ useEffect,useState } from "react";
import { StyleSheet } from "react-native";
import { SafeAreaProvider } from "react-native-safe-area-context";

import { Formik } from "formik";
import * as Yup from "yup";
import AppFormField from "../components/AppFormField";
import { Button } from "react-native-elements";
import { useDispatch,useSelector } from "react-redux";
import { ADD_REMINDER } from "../store/remiders/reminders.action";
import AppFormDatePicker from "../components/AppFormDatePicker";
import DateTimeModalPicker from "react-native-modal-datetime-picker";
import dayjs from "dayjs";
import { LocalScheduleNotification } from "../services/LocalPushController";
import moment from "moment";
import { useNavigation } from "@react-navigation/core";
import AppFormPicker from "../components/AppFormPicker";
import { ScrollView } from "react-native-gesture-handler";
import calcNext,{ addDate,isScheduleBehind } from "../utils/calcSchedule";

const initialValues = {
  title: "",description: "",isDatePick: false,isTimePick: true,isRepeat: false,};

const options = [
  { label: "Daily",value: "day" },{ label: "Weekly",value: "week" },{ label: "Monthly",value: "month" },];

const validationSchema = Yup.object().shape({
  title: Yup.string().required().min(4).label("Title"),description: Yup.string().label("Description"),isDatePick: Yup.boolean().label("Date"),isTimePick: Yup.boolean().oneOf([true],"You must choose the reminded time"),isRepeat: Yup.boolean().label("Repeat"),});

const ReminderEditScreen = () => {
  const dispatch = useDispatch();
  const navigation = useNavigation();
  const { lastId } = useSelector((state) => state.reminders);
  const [date,setDate] = useState(new Date(Date.now()));
  const [time,setTime] = useState(dayjs().add(5,"minutes").toDate());
  const [pickSchedule,setPickSchedule] = useState(
    dayjs().add(5,"minutes").toDate()
  );
  const [visible,setVisible] = useState(false);
  const [mode,setMode] = useState("time");
  const [repeatValue,setRepeatValue] = useState(options[0].value);
  const [minDate,setMinDate] = useState(new Date(Date.now()));

  const handleAddReminder = (values) => {
    const validId = lastId + 1;

    console.log(pickSchedule);

    const notiConfig = {
      title: values.title,description: `${values.description}`,repeatType: values.isRepeat ? repeatValue : null,};

    LocalScheduleNotification(pickSchedule,validId,notiConfig);
    dispatch({
      type: ADD_REMINDER,payload: {
        ...values,id: validId,repeatType: values.isRepeat
          ? options.find((type) => type.value === repeatValue).label
          : null,date: dayjs(pickSchedule).format(),},});

    navigation.navigate("Home");
  };

  const handleOpenPicker = (mode) => {
    setMode(mode);
    setVisible(true);
  };

  const handleDatePick = (date) => {
    const pickDate = moment(date);
    const pickTime = moment(time);
    const newDate = new Date(
      pickDate.year(),pickDate.month(),pickDate.date(),pickTime.hours(),pickTime.minutes(),pickTime.seconds(),pickTime.milliseconds()
    );
    setPickSchedule(newDate);
    setDate(date);
    setVisible(false);
  };

  const handleTimePick = (time) => {
    let calcDate = date;
    if (isScheduleBehind(dayjs(time),dayjs())) {
      setMinDate(addDate(dayjs()).toDate());
      calcDate = addDate(dayjs(date)).toDate();
    } else {
      setMinDate(dayjs().toDate());
    }
    const pickDate = moment(calcDate);
    const pickTime = moment(time);
    const newDate = new Date(
      pickDate.year(),pickTime.milliseconds()
    );
    setPickSchedule(newDate);
    setTime(time);
    setDate(calcDate);
    setVisible(false);
  };

  return (
    <ScrollView>
      <SafeAreaProvider style={styles.container}>
        <Formik
          initialValues={initialValues}
          validationSchema={validationSchema}
          onSubmit={handleAddReminder}
        >
          {({ handleSubmit,setFieldValue,values }) => {
            return (
              <>
                <AppFormField name="title" placeholder="Title" />
                <AppFormField
                  name="description"
                  placeholder="Description"
                  numberOfLines={3}
                />
                <AppFormDatePicker
                  pickerMode="time"
                  icon="calendar-clock"
                  value={dayjs(time).format("HH:mm")}
                  name="isTimePick"
                  onOpen={handleOpenPicker}
                  title="Set Time"
                  onToggle={() =>
                    setFieldValue("isTimePick",!values["isTimePick"])
                  }
                />
                <AppFormDatePicker
                  pickerMode="date"
                  icon="calendar-today"
                  value={dayjs(date).format("DD/MM/YYYY")}
                  name="isDatePick"
                  onOpen={handleOpenPicker}
                  title="Set Date"
                  onToggle={() =>
                    setFieldValue("isDatePick",!values["isDatePick"])
                  }
                />
                <AppFormPicker
                  options={options}
                  title="Repeat"
                  icon="calendar-refresh"
                  name="isRepeat"
                  onToggle={() =>
                    setFieldValue("isRepeat",!values["isRepeat"])
                  }
                  onPick={(item) => setRepeatValue(item)}
                  selectedValue={repeatValue}
                />
                <DateTimeModalPicker
                  is24Hour={true}
                  minimumDate={minDate}
                  mode={mode}
                  isVisible={visible}
                  onCancel={() => setVisible(false)}
                  onConfirm={mode === "date" ? handleDatePick : handleTimePick}
                />
                <Button
                  title="REMIND ME"
                  onPress={handleSubmit}
                  buttonStyle={styles.button}
                />
              </>
            );
          }}
        </Formik>
      </SafeAreaProvider>
    </ScrollView>
  );
};

const styles = StyleSheet.create({
  container: {
    marginVertical: 20,marginHorizontal: 10,button: {
    borderRadius: 10,paddingVertical: 15,});

export default ReminderEditScreen;

index.js

import { AppRegistry } from "react-native";
import App from "./App";
import { name as appName } from "./app.json";
import { PushNotificationInit } from "./src/services/LocalPushController";

PushNotificationInit();

AppRegistry.registerComponent(appName,() => App);

解决方法

暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!

如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。

小编邮箱:dio#foxmail.com (将#修改为@)