この記事は公開されてから1年以上経過しています。情報が古い可能性がありますので、ご注意ください。
はじめに
こんにちは。iOS 10 と watchOS 3 快適ですね!田宮です。
WWDC参加のためサンフランシスコにいたのが3ヶ月前。とうとう iOS 10 が正式公開されました!!
前記事「[iOS 10] User Notifications framework を使用してアプリがフォアグラウンドの時でも通知バナーを表示する方法 #wwdc」では、アプリがフォアグラウンドの時でも通知バナーを表示する方法をご紹介しました。
本記事では、iOS 10で登録済みの通知を更新・削除する方法をご紹介します。
実装
通知の登録については、第1回目の記事をご参照下さい。
通知の削除
下記のように、removePendingNotificationRequestsメソッドを使うと、一度登録した通知を、発火前の任意のタイミングで削除することが可能です。
// 通知の定義
let id = "notification.identifier"
let request = UNNotificationRequest(identifier: id,
content: content,
trigger: startTrigger)
// 通知の登録
UNUserNotificationCenter.current().add(request) { (error) in // ... }
// 通知の削除
UNUserNotificationCenter.current().removePendingNotificationRequests(withIdentifiers: [id])
通知の更新
まずは通知を登録します。
// 通知の定義(旧)
let id = "notification.identifier"
let request = UNNotificationRequest(identifier: id,
content: content,
trigger: startTrigger)
// 通知の登録
UNUserNotificationCenter.current().add(request) { (error) in // ... }
そして、更新したい通知のidentifierを使ってUNNotificationRequest新たに生成します。
それをUNUserNotificationCenterのaddメソッドに受け渡せば、OKです。
この際、更新前の通知について、削除をする必要はありません。
// 通知の定義(新)
let updatedRequest = UNNotificationRequest(identifier: id,
content: newContent, // 新しいcontent
trigger: newStartTrigger) // 新しいtrigger
// 新しい通知の登録
UNUserNotificationCenter.current().add(updatedRequest) { (error) in // ... }
さいごに
本記事では、登録済みの通知を更新・削除する方法を紹介しました。
今後も User Notifications framework のクラスを試していきます!
参考資料
Framework Reference
- UserNotifications - Apple Developer Documentation
- Introduction to Notifications - WWDC 2016 - Videos - Apple Developer