はじめに
私は以前、以下のような記事を書きました。
Ionic ローカルでプッシュ通知のテスト (Capacitor)
ローカルプッシュ通知を出す訳ですが、上記の記事には重大な問題があった。。
そう、通知をストップさせる術を書いていないのだ!!!
最近気づいたのだが、every
のタイプでローカルプッシュ通知を設定した場合、該当するコードを削除してもずっと通知が来る。。。
詳しく書くよ
こちらの記事では、最終的に以下のようなコードとなった
import { Injectable } from '@angular/core';
import { Plugins } from '@capacitor/core';
const { LocalNotifications } = Plugins;
@Injectable({
providedIn: 'root'
})
export class PushService {
constructor() { }
LocalNotifications() {
// 5秒後に通知が来る
const date = new Date(Date.now() + 1000 * 5);
LocalNotifications.schedule({
notifications: [
{
title: 'Title',
body: 'Body',
id: 1,
schedule: { every: 'day' },
sound: null,
attachments: null,
actionTypeId: '',
extra: null
}
]
});
}
}
あとはLocalNotifications()
を任意のhome.page.ts
にて呼び出しましょう。
import { PushService } from './../service/push.service';
constructor(
private pushService: PushService
) {
this.pushService.LocalNotifications();
}
しかし、これらのコードを全てコメントアウトしても、毎日通知が来るのである!!
home.page.ts
で呼び出されているlocationNotification()
を消せは、通知が止まると思っていたが、全くそうではなかったようだ。。
結論、キャンセルの処理を書こう!
こちらの記事を参考としました。(ただしあまりよくわかっていない)
import { Injectable } from '@angular/core';
import { Plugins } from '@capacitor/core';
const { LocalNotifications } = Plugins;
@Injectable({
providedIn: 'root'
})
export class PushService {
constructor() { }
LocalNotifications() {
// 5秒後に通知が来る
const date = new Date(Date.now() + 1000 * 5);
LocalNotifications.schedule({
notifications: [
{
title: 'Title',
body: 'Body',
id: 1,
schedule: { every: 'day' },
sound: null,
attachments: null,
actionTypeId: '',
extra: null
}
]
});
}
stopLocalPush() {
LocalNotifications.getPending().then(res => {
LocalNotifications.cancel(res);
}, error => {
console.log(error);
});
}
}
import { PushService } from './../service/push.service';
constructor(
private pushService: PushService
) {
this.pushService.LocalNotifications();
this.pushService.stopLocalNotifications();
}
恐らくthis.pushService.stopLocalNotifications()
を設定ページなんかに置けば、ユーザー側で制御できるって感じだろうか??
とりあえず、こんなへっぽこな例だがローカルプッシュ通知をストップさせる事には成功した!
使い方がいまいち分かっていないです。。。
最後に
参考としたこちらの記事だが、誰か詳しく解説して欲しいです。。
I have found a solution. As said Mostafa I got all the pending notifications and then I have an array with all its ids.
With these ids and splice I can modify the array removing all the notifications that I don't want to delete and after that I cancel all the notifications of the array.
I leave here the method that I'm using in this case to delete all te notifcations except the notification con id 10000000.
LocalNotifications.getPending().then( res => {
var index = res.notifications.map(x => {
return x["id"];
}).indexOf("10000000");
res.notifications.splice(index, 1);
LocalNotifications.cancel(res);
}, err => {
console.log(err);
})
これはid
が10000000
のローカルプッシュ通知以外をキャンセルしている、って事かな??!