Swift:在点击推送通知操作按钮并对其进行处理时,在文本字段中编写

时间:2018-07-17 15:40:53

标签: ios swift xcode unusernotificationcenter

我正在使用Xcode 9.4.1 (9F2000)Swift

我在AppDelegate中有此代码:

func showPushButtons(){
    let replyAction = UNNotificationAction(
        identifier: "reply.action",
        title: "Reply to this message",
        options: [])

    let pushNotificationButtons = UNNotificationCategory(
        identifier: "allreply.action",
        actions: [replyAction],
        intentIdentifiers: [],
        options: [])

    UNUserNotificationCenter.current().setNotificationCategories([pushNotificationButtons])
}
func userNotificationCenter(_ center: UNUserNotificationCenter, didReceive response: UNNotificationResponse, withCompletionHandler completionHandler: @escaping () -> Void) {

    let action = response.actionIdentifier
    let request = response.notification.request
    let content = response.notification.request.content.userInfo

    if action == "reply.action"{
        print("Reply button clicked")

        completionHandler()
    }
}

这使得以下内容:

收到推送通知时,将显示一个名为Reply to this message的操作按钮。

当前,单击按钮时,控制台将打印Reply button clicked

我想做什么:

如果我单击按钮,则将出现一个文本字段和键盘(从消息传递应用程序中得知)。编写一些文本并提交/发送后,我想在AppDelegate中接收此消息以进行处理。

您知道如何执行此操作吗?有提示吗?

2 个答案:

答案 0 :(得分:1)

此代码现在有效:

func showPushButtons(){
    let replyAction = UNTextInputNotificationAction(
        identifier: "reply.action",
        title: "Reply on message",
        textInputButtonTitle: "Send",
        textInputPlaceholder: "Input text here")

    let pushNotificationButtons = UNNotificationCategory(
        identifier: "allreply.action",
        actions: [replyAction],
        intentIdentifiers: [],
        options: [])

    UNUserNotificationCenter.current().setNotificationCategories([pushNotificationButtons])
}
func userNotificationCenter(_ center: UNUserNotificationCenter, didReceive response: UNNotificationResponse, withCompletionHandler completionHandler: @escaping () -> Void) {

    if  response.actionIdentifier  ==  "reply.action" {
        if let textResponse =  response as? UNTextInputNotificationResponse {
            let sendText =  textResponse.userText
            print("Received text message: \(sendText)")
        }
    }
    completionHandler()
}

它的作用:如果您收到带有"category":"allreply.action"的推送通知,并在其中强行单击,将显示一个文本字段和键盘,您可以使用{{1}进行打印}。

别忘了从print("Received text message: \(sendText)")调用showPushButtons()并为接收(远程)推送通知准备应用程序。

答案 1 :(得分:0)

用这个替换您的replyAction

let replyAction = UNTextInputNotificationAction(identifier: "reply.action", title: "message", options: [], textInputButtonTitle: "Send", textInputPlaceholder: "type something …")

这应该可以解决您的问题。