eri1208
@eri1208

Are you sure you want to delete the question?

If your question is resolved, you may close it.

Leaving a resolved question undeleted may help others!

We hope you find it useful!

Swift ローカル通知でのカスタム通知アクションについて

解決したいこと

ローカル通知で、下記リンク先のように、ボタンを追加してユーザーに何かしらの選択をさせる機能を実装したいのですが、うまくいきません。
https://crossbridge-lab.hatenablog.com/entry/2016/10/25/114520

下記コードで実装すると、通知は来るよになったのですが、タイトルとボディだけで、ボタンのyes/noが実装されません。

実装コード:通知の権限をリクエスト

import UserNotifications
import SwiftUI

func requestNotificationPermission() {
    UNUserNotificationCenter.current().requestAuthorization(options: [.alert, .sound, .badge]) { granted, error in
        if granted {
            print("Notification permission granted.")
        } else {
            print("Notification permission denied.")
        }
    }
}

実装コード:通知アクション定義

func setupNotificationActions() {
    let yesAction = UNNotificationAction(identifier: "YES_ACTION", title: "Yes", options: [.foreground])
    let noAction = UNNotificationAction(identifier: "NO_ACTION", title: "No", options: [])
    
    let category = UNNotificationCategory(identifier: "CHOICE_CATEGORY", actions: [yesAction, noAction], intentIdentifiers: [], options: [])
    
    // カスタムアクションを登録
    UNUserNotificationCenter.current().setNotificationCategories([category])
}

実装コード:通知スケジュール

func scheduleNotification() {
    let content = UNMutableNotificationContent()
    content.title = "Select an option"
    content.body = "Do you want to proceed?"
    content.categoryIdentifier = "CHOICE_CATEGORY"  // カスタムアクションを適用
    content.sound = UNNotificationSound.default
    
    let trigger = UNTimeIntervalNotificationTrigger(timeInterval: 5, repeats: false)
    let request = UNNotificationRequest(identifier: "LOCAL_NOTIFICATION", content: content, trigger: trigger)
    
    UNUserNotificationCenter.current().add(request) { error in
        if let error = error {
            print("Error scheduling notification: \(error)")
        }
    }
}

実装コード:通知アクションの応答処理

class NotificationDelegate: NSObject, UNUserNotificationCenterDelegate {
    // ユーザーが通知のアクションを選択したときに呼ばれる
    func userNotificationCenter(_ center: UNUserNotificationCenter, didReceive response: UNNotificationResponse, withCompletionHandler completionHandler: @escaping () -> Void) {
        if response.actionIdentifier == "YES_ACTION" {
            print("User selected Yes")
            // Yes アクションの処理をここに記述
        } else if response.actionIdentifier == "NO_ACTION" {
            print("User selected No")
            // No アクションの処理をここに記述
        }
        completionHandler()
    }
}

実装コード:アプリ起動時設定

@main
struct YourApp: App {
    @UIApplicationDelegateAdaptor(AppDelegate.self) var appDelegate

    var body: some Scene {
        WindowGroup {
            ContentView()
        }
    }
}

class AppDelegate: NSObject, UIApplicationDelegate {
    let notificationDelegate = NotificationDelegate()
    
    func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey : Any]? = nil) -> Bool {
        // 通知のデリゲートを設定
        UNUserNotificationCenter.current().delegate = notificationDelegate
        
        // 通知の権限をリクエスト
        requestNotificationPermission()
        
        // カスタム通知アクションのセットアップ
        setupNotificationActions()
        
        return true
    }
}

原因わかる方、教えていただけると助かります。

0

1Answer

コードの問題ではなく、表示させ方だと思います。
アクションを表示させるためには、下記動画のように、ドラッグする必要があります。
もしくは、長押しする。

qa4.gif
1Like

Comments

  1. @eri1208

    Questioner

    なるほど!ありがとうございます!
    ちなみに、ドラッグや長押しが必要なくなる(最初から表示)させる方法はなさそうですかね。。。

Your answer might help someone💌