0
0

More than 3 years have passed since last update.

Ionic ローカルプッシュ通知を毎月指定の日に出す(Capacitor)

Posted at

はじめに

ローカルプッシュ通知の出し方についてはこちら:point_down:
Ionic ローカルでプッシュ通知のテスト (Capacitor)

この記事ではローカルプッシュ通知を毎月はじめの日に出す(3月1日とか)

javascriptのDateクラスを使おう

コード全文を見たい方は、「はじめに」で載せてあるリンクからお願いします。。

LocalNotifications() {
    // システム日時の1日を取得する
    const date = new Date();
    const nextMonth = new Date(
       date.getFullYear(),
       date.getMonth() + 1,
       1
    );

    LocalNotifications.schedule({
      notifications: [
        {
          title: '今月もはじめりましたね!',
          body: '張り切っていきましょう!',
          id: 1,
          schedule: { at: nextMonth },
          sound: null,
          attachments: null,
          actionTypeId: '',
          extra: null
        }
      ]
    });
  }

問題点

setDate(1)は使えない

こちらで紹介されているやり方だと、残念ながらできません。。
notificationsの中のscheduleの値はDate型じゃないといけないようです。

atはアプリが起動するたびにリセットされる

例えば下記の例だと、アプリを起動して1分後に通知が来る。
しかし、アプリ起動中に1分ごとに通知が来たりはしない。
おそらくこれはatだから。(もっとも1分おきの通知ならevery : minuteで事足りる訳だが、、)

LocalNotifications() {
    const date = new Date();
   // 1分後
    const nextMoment = new Date(
      date.getFullYear(),
      date.getMonth(),
      date.getDate(),
      date.getHours(),
      date.getMinutes() + 1
    );

    LocalNotifications.schedule({
      notifications: [
        {
          title: '1分',
          body: '麺が硬いですね〜',
          id: 1,
          schedule: { at: nextMoment },
          sound: null,
          attachments: null,
          actionTypeId: '',
          extra: null
        }
      ]
    });
  }

つまり、月初に毎月通知を出そうとするなら、最低1回はアプリを起動してもらわないといけない事になる。。(恐らく!)

every : monthだと絶対に毎月1日!とか、指定できないっぽいので困りものである。。

この辺の挙動については、ぜひご自身で実験してほしい。

日付の指定で参考になるサイト

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0