[iOS 10] User Notifications framework を使用して「カスタム通知アクション付のリモート通知」を作成する #wwdc

2016.07.11

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

はじめに

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

本記事では、「カスタム通知アクション付のリモート通知」を作成する実装を紹介します。

「カスタム通知アクション付のローカル通知」の作成方法はこちらの記事で、「カスタム通知アクション無しのリモート通知」の作成方法についてはこちらの記事で解説していますので、あわせてお読みください。

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

検証環境

  • Xcode Version 8.0 beta 2 (8S162m)
  • iPhone 6s
    • iOS 10.0 (14A5297c)

実装

それでは、「カスタム通知アクション付のリモート通知」を作成する方法を解説していきます。

通知のカテゴリを作成する

記事「User Notifications framework を使用して「カスタム通知アクション付のローカル通知」を作成する」と同じ手順で通知のカテゴリを作成します。

// UNNotificationAction を作成
let action = UNNotificationAction(identifier:"replyActionIdentifier",
                                  title:"Reply",
                                  options:[])

// UNNotificationCategory を作成
let category = UNNotificationCategory(identifier: "messageCategoryIdentifier",
                                      actions: [action],
                                      minimalActions: [action],
                                      intentIdentifiers: [],
                                      options: [])

// UNUserNotificationCenter に追加
UNUserNotificationCenter.current().setNotificationCategories([category])

通知アクションが選択された時のイベントをハンドリングする

こちらも、記事「User Notifications framework を使用して「カスタム通知アクション付のローカル通知」を作成する」と同様の手順で実装します。

// 任意のオブジェクトを UNUserNotificationCenter のデリゲートにする
UNUserNotificationCenter.current().delegate = self
func userNotificationCenter(_ center: UNUserNotificationCenter,
                            didReceive response: UNNotificationResponse,
                            withCompletionHandler completionHandler: () -> Void) {
    // リモート通知かローカル通知かを判別する
    if notification.request.trigger is UNPushNotificationTrigger {
        print("didReceive PushNotification")

        // action ID を判別する
        if response.actionIdentifier == "replyActionIdentifier" {
            print("Selected Reply Action!!")
        }
    }

    ...

    // 処理完了時に呼ぶ
    completionHandler()
}

通知を送信する

任意の方法で APNs にペイロードを送信します。

ペイロードの JSON の内容は、記事「User Notifications framework を使用してリモート通知を受け取る処理を実装する」で解説したものとほとんど同じです。

リモート通知にカスタム通知アクションを追加するには、以下のように category キーを追加して値としてカテゴリの identifier を指定します。ここで指定する identifier は、手順「通知のカテゴリを作成する」で作成したカテゴリの identifier です。

{
  "aps": {
    "alert": {
      "title": "Introduction to Notifications",
      "subtitle": "Session 707",
      "body": "Woah! These new notifications look amazing! Don’t you agree?"
    },
    "badge": 1,
    "category": "messageCategoryIdentifier"
  }
}

さいごに

本記事では「カスタム通知アクション付のリモート通知」を作成する実装を紹介しました。

次回の記事では、カスタム通知アクションの「オプション」について解説する予定です。お楽しみに!

参考資料