0Pricing
Swift Academy · レッスン

通知のアクションとカテゴリ

通知にインタラクティブなアクションを追加します。

「通知のアクションとカテゴリ」はCoddyKit上の無料Swift Academyレッスンです。 これはレッスン4/4です。 下記で完全なレッスンを無料で読むことができます。その後、ブラウザ内の組み込みコードエディタと24時間対応のAIチューターでハンズオン演習できます。 これはSwift Academy学習パスの一部であり、ウェブとCoddyKitアプリ全体で進捗が同期されます。 Swift Academyコースには全4レッスンが含まれています。

インタラクティブ通知

通知はテキストを表示するだけでなく、ボタンも提供できます。ユーザーはアプリを開かずに、メッセージへの返信、招待の承諾、リマインダーのスヌーズなどを行えます。これはアクションをカテゴリにまとめて構成します。

import UserNotifications
// Category = a set of actions
// Each delivered notification names its category
// so the system shows the right buttons

アクションの定義

UNNotificationActionには、後で照合する識別子、ボタンに表示するローカライズ可能なタイトル、.destructiveや.foreground(アプリを起動する)などのオプションがあります。

import UserNotifications
let accept = UNNotificationAction(
    identifier: "ACCEPT",
    title: String(localized: "Accept"),
    options: [.foreground])
let decline = UNNotificationAction(
    identifier: "DECLINE",
    title: String(localized: "Decline"),
    options: [.destructive])

カテゴリへのグループ化

UNNotificationCategoryは、カテゴリ識別子の下にアクションをまとめます。配列内のアクションの順序が、そのままボタンの順序になります。カテゴリは起動時に通知センターへ一度登録します。

import UserNotifications
let inviteCategory = UNNotificationCategory(
    identifier: "INVITE",
    actions: [accept, decline],
    intentIdentifiers: [],
    options: [])
UNUserNotificationCenter.current()
    .setNotificationCategories([inviteCategory])

通知へのカテゴリの付与

ボタンを表示するには、通知のコンテンツでcategoryIdentifierに登録済みのカテゴリを指定する必要があります。リモートプッシュの場合、サーバーはaps辞書内に"category": "INVITE"を送信します。

import UserNotifications
let content = UNMutableNotificationContent()
content.title = String(localized: "New invite")
content.body = String(localized: "Ada invited you")
content.categoryIdentifier = "INVITE"

選択されたアクションの処理

ユーザーがボタンをタップすると、response.actionIdentifierにアクションIDが設定された状態で、デリゲートのdidReceive responseが呼び出されます。値に応じて分岐し、適切な処理を実行します。

import UserNotifications
func userNotificationCenter(
    _ center: UNUserNotificationCenter,
    didReceive response: UNNotificationResponse
) async {
    switch response.actionIdentifier {
    case "ACCEPT":  print("accepted")
    case "DECLINE": print("declined")
    default:        break
    }
}

デフォルト識別子と解除識別子

システム識別子は常に2つ存在します。UNNotificationDefaultActionIdentifierはユーザーが本文をタップしてアプリを開いたことを示し、UNNotificationDismissActionIdentifierは通知を解除したことを示します。これらもカスタムアクションと合わせて処理してください。

import UserNotifications
func route(_ id: String) {
    switch id {
    case UNNotificationDefaultActionIdentifier:
        print("opened the app")
    case UNNotificationDismissActionIdentifier:
        print("dismissed")
    default:
        print("custom action", id)
    }
}

テキスト入力アクション

UNTextInputNotificationActionは、通知内にテキストフィールドを表示します。簡単な返信に最適です。入力ボックスのボタンタイトルとプレースホルダーを追加で指定できます。

import UserNotifications
let reply = UNTextInputNotificationAction(
    identifier: "REPLY",
    title: String(localized: "Reply"),
    options: [],
    textInputButtonTitle: String(localized: "Send"),
    textInputPlaceholder: String(localized: "Message"))

入力されたテキストの読み取り

テキストアクションに対するレスポンスはUNTextInputNotificationResponseです。これにキャストして、ユーザーが入力した文字列であるuserTextを読み取ります。

import UserNotifications
func handle(_ response: UNNotificationResponse) {
    if let textResponse = response
        as? UNTextInputNotificationResponse {
        let message = textResponse.userText
        print("reply:", message)
    }
}

カテゴリオプション

カテゴリオプションで動作を細かく調整できます。.customDismissActionを指定すると解除イベントがデリゲートに通知され、.hiddenPreviewsShowTitleを指定するとロック画面でプレビューを非表示にしていてもタイトルが表示され、.allowInCarPlayを指定するとCarPlayでの表示が許可されます。

import UserNotifications
let category = UNNotificationCategory(
    identifier: "MESSAGE",
    actions: [reply],
    intentIdentifiers: [],
    options: [.customDismissAction,
              .hiddenPreviewsShowTitle])
_ = category

バックグラウンドアクションとフォアグラウンドアクション

.foregroundオプションを指定しない場合、アクションはアプリを前面に表示せず、バックグラウンドでハンドラーを実行します。スヌーズや「いいね」などに適しています。.foregroundを指定するとアプリが起動するため、UIを表示できます。ユーザーが画面を見る必要があるかどうかに応じて選択してください。

import UserNotifications
let snooze = UNNotificationAction(
    identifier: "SNOOZE",
    title: String(localized: "Snooze"),
    options: []) // background, no app launch
let open = UNNotificationAction(
    identifier: "OPEN",
    title: String(localized: "Open"),
    options: [.foreground]) // launches app
_ = (snooze, open)

完全な返信フロー

テキストアクション、カテゴリ、入力された返信と単なる起動を区別するハンドラーを組み合わせます。このパターンによって、インラインメッセージ返信を実現できます。

import UserNotifications
func handle(_ response: UNNotificationResponse) async {
    switch response.actionIdentifier {
    case "REPLY":
        let text = (response as?
            UNTextInputNotificationResponse)?.userText ?? ""
        print("send reply:", text)
    case UNNotificationDefaultActionIdentifier:
        print("open conversation")
    default:
        break
    }
}

クイックチェック

表示するボタンをシステムがどのように判断するか思い出してください。

まとめ

インタラクティブ通知を学びました:

  • UNNotificationAction(UNTextInputNotificationActionを含む)を作成し、UNNotificationCategoryにまとめます。
  • 起動時にカテゴリを登録し、コンテンツにcategoryIdentifierを設定します(プッシュではcategoryを設定します)。これによりボタンが表示されます。
  • response.actionIdentifierを処理します。デフォルト識別子と解除識別子も処理し、返信の場合はuserTextを読み取ります。
  • スヌーズなどのバックグラウンドアクションでは.foregroundを省略します。

よくある質問

「通知のアクションとカテゴリ」レッスンは無料ですか?

はい。「通知のアクションとカテゴリ」の完全なテキストはこのウェブで無料で読めます。インタラクティブに演習し(組み込みコードエディタと24時間対応のAIチューター)、Swift Academyコースの残りをアンロックするには、CoddyKit PROにアップグレードしてください。 Swift Academyコースには全4レッスンが含まれています。

「通知のアクションとカテゴリ」で何を学びますか?

通知にインタラクティブなアクションを追加します。 ブラウザで直接実行するハンズオンコードでSwift Academyを演習し、24時間対応のAIチューターがレッスンを進める中での質問に答えます。

Swift Academyを始めるのに経験は必要ですか?

事前経験は必要ありません。CoddyKitのSwift Academyは初級者から上級者向けに構成されているため、ここから始めるか最初から始めて、自分のペースで進むことができます。 これはレッスン4/4です。

「通知のアクションとカテゴリ」レッスンにはどのくらい時間がかかりますか?

ほとんどのCoddyKitレッスンは約5~10分かかります。各レッスンはコンパクトでインタラクティブなので、着実に進歩し、ウェブとアプリ全体で正確に前回の場所から再開できます。

このSwift Academyレッスンでコードを書いて実行できますか?

はい。すべてのSwift Academyレッスンに組み込みコードエディタが含まれているため、ブラウザでリアルコードを書いて実行し、即座のAIフィードバックを取得できます。ローカル設定は不要です。

このコースのすべてのレッスン

  1. プッシュ通知への登録
  2. 通知ペイロードの処理
  3. バックグラウンドタスクと更新
  4. 通知のアクションとカテゴリ
← Swift Academyに戻る