[iOS 10] User Notifications framework を使用して時限式のローカル通知を作成する #wwdc

2016.06.15

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

はじめに

こんばんは。モバイルアプリサービス部の平屋です。

iOS 10 で追加された「User Notifications framework」のクラスを使用してローカル通知を飛ばす実装を試してみましたので紹介します。

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

User Notifications framework

「User Notifications framework」が提供する主な機能は以下の通りです。

  • 時間や場所のような条件に基づいたローカル通知をスケジューリング
  • ローカル・リモート通知の受信をハンドリング
  • ユーザーのデバイスに配信されたときに、必要に応じて通知内容を変更

実装

ユーザーの許可を得る

通知を飛ばすには、まず、ユーザーの許可を得る必要があります。

UNUserNotificationCenter クラスの requestAuthorization メソッドを使用してユーザーの許可をリクエストします。UNUserNotificationCenter クラスは通知のスケジュールや通知周りの処理を管理するクラスです。

// current() メソッドを使用してシングルトンオブジェクトを取得
let center = UNUserNotificationCenter.current()

// 通知の使用許可をリクエスト
center.requestAuthorization([.alert, .sound]) { (granted, error) in
    // Enable or disable features based on authorization.
}

はじめてリクエストしたタイミングで、許可を求めるアラートが表示されます。

ローカル通知を作成する

UNMutableNotificationContentUNTimeIntervalNotificationTrigger から UNNotificationRequest を作成し、UNUserNotificationCenter に追加します。

それぞれのクラスの役割は以下の通りです。

クラス名 役割
UNMutableNotificationContent 通知のタイトル、本文、サウンド設定などを保持
UNTimeIntervalNotificationTrigger 指定時間後に発火するタイプの通知の発火条件を保持する
UNNotificationRequest 通知のコンテンツやトリガーを保持する
// UNMutableNotificationContent 作成
let content = UNMutableNotificationContent()
content.title = "Hello!"
content.body = "World!"
content.sound = UNNotificationSound.default()

// 5秒後に発火する UNTimeIntervalNotificationTrigger 作成、
let trigger = UNTimeIntervalNotificationTrigger.init(timeInterval: 5, repeats: false)

// identifier, content, trigger から UNNotificationRequest 作成
let request = UNNotificationRequest.init(identifier: "FiveSecondNotification", content: content, trigger: trigger)

// UNUserNotificationCenter に request を追加
let center = UNUserNotificationCenter.current()
center.add(request)

通知受信時の処理を実装する

アプリが foreground ではない場合は、システム提供の通知 UI が表示されますが、foreground の時に通知を受け取った時の処理は自前で実装する必要があります。

任意のオブジェクトを UNUserNotificationCenter のデリゲートにして、デリゲートメソッドを実装すれば OK です。

// デリゲートを設定
center.delegate = self;
// アプリが foreground の時に通知を受け取った時に呼ばれるメソッド
func userNotificationCenter(_ center: UNUserNotificationCenter, willPresent notification: UNNotification, withCompletionHandler completionHandler: (UNNotificationPresentationOptions) -> Void) {
    print("fire! notification ID:\(notification.request.identifier)")

}

さいごに

本記事では User Notifications framework を使用して時限式のローカル通知を飛ばす実装を紹介しました。

ローカル通知のトリガーには、指定日に発火させるものや、位置情報に基づいて発火させるものがあるようなので、次回はこれらを使ったローカル通知を試してみようと思います!

参考資料

Framework Reference

Class Reference