UNTextInputNotificationActionを使ってテキスト入力可能なプッシュを送る
テキスト入力可能なプッシュ
カスタム通知アクションについては前回の記事で解説しましたが、今回はその続きでテキスト入力可能なPUSH通知について解説します。
UNTextInputNotificationAction
通知が届いたときにユーザーにテキストを入力してもらうUIはUNTextInputNotificationAction
を使うことで実現できます。UNTextInputNotificationAction
はUNNotificationAction
を継承しています。UNNotificationAction
にもあったidentifier
、title
、options
に加えて、textInputButtonTitle
とtextInputPlaceholder
が増えています。それぞれ、TextFiledに横に表示されるボタンのタイトル、プレースホルダーの文字列を指定します。
let okAction = UNNotificationAction(identifier: "action_ok", title: "OK", options: [.foreground]) let ngAction = UNNotificationAction(identifier: "action_ng", title: "NG", options: [.destructive, .foreground]) let textInputAction = UNTextInputNotificationAction(identifier: "action_input", title: "コメント", options: [], textInputButtonTitle: "送信", textInputPlaceholder: "コメントを入力する") let category = UNNotificationCategory(identifier: "category_select", actions: [okAction, ngAction, textInputAction], intentIdentifiers: [], options: []) let center = UNUserNotificationCenter.current() center.setNotificationCategories([category]) center.delegate = self center.requestAuthorization(options: [.alert, .badge, .sound]) { if $0.0 { let application = UIApplication.shared application.registerForRemoteNotifications() } }
入力されたテキストを取得する
入力されたテキストはuserNotificationCenter(_:didReceive:withCompletionHandler:)
内でresponseをUNTextInputNotificationResponse
にキャストしてuserText
プロパティから取得します。
func userNotificationCenter(_ center: UNUserNotificationCenter, didReceive response: UNNotificationResponse, withCompletionHandler completionHandler: @escaping () -> Swift.Void) { switch response.actionIdentifier { case "action_ok": break case "action_NG": break case "action_input": if let response = response as? UNTextInputNotificationResponse { print(response.userText) } break default: // アクションではなく通知自体をタップしたときは UNNotificationDefaultActionIdentifier が渡ってくる break } completionHandler() }