[iOS 10] UNUserNotificationCenter を使用して未配信の通知を管理する #wwdc

2016.06.17

この記事は公開されてから1年以上経過しています。情報が古い可能性がありますので、ご注意ください。

はじめに

こんにちは。モバイルアプリサービス部の平屋です。前回の記事に引き続き、iOS 10 で追加された「User Notifications framework」のクラスを使用した実装を紹介します。

以下の記事でローカル通知を作成する手順を解説しました。

本記事では、上記記事の手順で作成されてまだ配信されていない通知を管理する方法を紹介します。

本記事は Apple からベータ版として公開されているドキュメントを情報源としています。 そのため、正式版と異なる情報になる可能性があります。ご留意の上、お読みください。

実装

未配信の通知を管理するには、UNUserNotificationCenter のメソッドを使用します。UNUserNotificationCenter は、以前の記事で通知を登録する際に使用しました。

未配信の通知の一覧を取得する

未配信の通知の一覧を取得するには UNUserNotificationCentergetPendingNotificationRequests(completionHandler:) メソッドを使用します。

取得処理は非同期で実行されます。処理完了時に呼ばれるハンドラはの引数は UNNotificationRequest の配列となっていて、UNNotificationRequest は、次に解説する「特定の未配信の通知を削除する」場合などに使用できます。

let center = UNUserNotificationCenter.current()
center.getPendingNotificationRequests { (requests: [UNNotificationRequest]) in

}

特定の未配信の通知を削除する

特定の未配信の通知を削除するには UNUserNotificationCenterremovePendingNotificationRequests(withIdentifiers:) メソッドを使用します。

引数には、削除したい UNNotificationRequestidentifier の配列をセットします。削除処理は非同期で実行されます。ローカル通知の場合のみ削除可能です。

let center = UNUserNotificationCenter.current()
center.removePendingNotificationRequests(withIdentifiers: [request.identifier])

全ての未配信の通知を削除する

全ての未配信の通知を削除するには UNUserNotificationCenterremoveAllPendingNotificationRequests() メソッドを使用します。

削除処理は非同期で実行されます。ローカル通知の場合のみ削除可能です。

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

さいごに

本記事では、未配信の通知を管理する方法を紹介しました。次回は通知センターに表示されている通知を管理する方法を試してみようと思います!

参考資料

Framework Reference

Class Reference