簡體   English   中英

如何使用 react-native-push-notification 永久刪除特定通知

[英]How to remove a specific notification forever using react-native-push-notification

我目前正在使用react-native-push-notification庫在我的 React Native 應用程序中安排和接收通知。 我可以使用 cancelLocalNotification 方法取消預定的通知,但這只會取消 24 小時的通知。 我想找到一種方法來永遠刪除特定的通知,這樣它就不會被重新安排。

我嘗試使用以下代碼通過其 ID 取消通知,但它只取消了 24 小時:

const onCancelNotification = async (id: string) => {
    // Get a list of all scheduled notifications
    PushNotification.getScheduledLocalNotifications((notifications) => {
      // Iterate through the list of notifications
      notifications.forEach((notification) => {
        // Check if the notification is the one you want to cancel
        if (notification.id.indexOf(id) === 0) {
          // Cancel the notification
          PushNotification.cancelLocalNotification(notification.id);
        }
      });
    });
  };

我將不勝感激有關如何實現這一目標的任何幫助或建議。

此代碼片段演示了在 React Native 中刪除特定計划的本地通知的解決方法。 function onRemoveNotification接收一個id參數,用於標識需要移除的具體通知。

重要的是要注意,在 React Native 中沒有直接的方法來刪除特定的計划本地通知。 此代碼提供了一種可以使用的解決方法,但請務必注意,它依賴於安排較早日期的通知並將repeatType設置為未定義。

請注意,此代碼不是完美的解決方案,可能會對應用程序產生副作用。

const onRemoveNotification = async (id: string) => {
  // Get a list of all scheduled notifications
  PushNotification.getScheduledLocalNotifications((notifications) => {
    // Iterate through the list of notifications
    notifications.forEach((notification) => {
      // Check if the notification is the one you want to cancel
      if (notification.data.notificationId?.indexOf(id) === 0) {
        // Create a new date one day earlier than the current scheduled date
        const earlyDate = moment(notification.date).add(-1, "day").toDate();
        // remove the notification
        // schedule the notification with an earlier date and repeat type undefined
        // this will effectively "remove" the notification
        // since it will not be displayed
        PushNotification.localNotificationSchedule({
          id: notification.id,
          title: notification.title,
          message: notification.message,
          repeatType: undefined,
          date: earlyDate,
        });
        // cancel the previous scheduled notification
        PushNotification.cancelLocalNotification(notification.id);
      }
    });
  });
};

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM