【SwiftUI】登録した通知を削除/更新/取得する方法!UNUserNotificationCenter

この記事からわかること

  • Swiftローカル通知削除する方法
  • removeAllPendingNotificationRequestsメソッドの使い方
  • removePendingNotificationRequests(withIdentifiers:)通知指定して削除するには?
  • 登録済みの通知を更新/取得する方法

index

[open]

\ アプリをリリースしました /

みんなの誕生日

友達や家族の誕生日をメモ!通知も届く-みんなの誕生日-

posted withアプリーチ

Swiftで登録済みのローカル通知を削除または更新する方法をまとめていきます。

ローカル通知を削除する

既にセットされたローカル通知を削除するには通知を管理しているUNUserNotificationCenterクラスのメソッドを使用します。

公式リファレンス:UNUserNotificationCenter

全て削除:removeAllPendingNotificationRequests

現在登録されている全ての通知情報を削除するにはremoveAllPendingNotificationRequestsメソッドを使います。

let center = UNUserNotificationCenter.current()
center.removeAllPendingNotificationRequests()

1つだけ削除:removePendingNotificationRequests(withIdentifiers:)

登録された通知のうち任意のものを1つだけ削除したい場合はremovePendingNotificationRequests(withIdentifiers:)メソッドを使用します。引数に通知登録時に指定した識別子を配列形式で渡すことで一致するものを全て削除します。

let center = UNUserNotificationCenter.current()
center.removePendingNotificationRequests(withIdentifiers: [id.uuidString])

通知を更新

登録された通知を更新するには同じ識別子を用いて再度登録処理を行えばOKです。

let request = UNNotificationRequest(identifier: "notice1", content: newContent, trigger: newTrigger)
// 再度登録処理
UNUserNotificationCenter.current().add(request)

通知を取得

セットされている通知を取得するにはgetPendingNotificationRequestsメソッドを使用します。

let center = UNUserNotificationCenter.current()
center.getPendingNotificationRequests { array in
  print(array)
}

ご覧いただきありがとうございました。

searchbox

スポンサー

ProFile

ame

趣味:読書,プログラミング学習,サイト制作,ブログ

IT嫌いを克服するためにITパスを取得しようと勉強してからサイト制作が趣味に変わりました笑
今はCMSを使わずこのサイトを完全自作でサイト運営中〜

New Article

index