选择推送通知的显示参数

时间:2019-06-28 09:26:04

标签: ios swift push-notification apple-push-notifications

我收到如下所示的推送通知:

{
    "aps" : {
        "alert" : {
            "loc-key" : "localized_pn_text",
            "loc-args" : [ "France", "Frank"]
        },
        "sound" : "chime.aiff"
    },
    "acme" : "foo"
}

现在,在我的Localizable.strings中,可以添加带有键"localized_pn_text"的字符串以本地化推送通知。

是否可以订购或选择特定参数。例如,我可以显示"Frank, you got a push notification"作为本地化文本吗?

3 个答案:

答案 0 :(得分:2)

您有两个选择:

  1. 在您的"localized_pn_text" = "%@, you got a push notification"中添加Localizable.strings,然后仅以"loc-args""loc-args" : [ "Frank"])的身份发送“ Frank”

  2. 在以下示例中,
  3. 实施Notification Service Extension来拦截推送通知并以编程方式创建其内容:

class NotificationService: UNNotificationServiceExtension {

    var contentHandler: ((UNNotificationContent) -> Void)?
    var bestAttemptContent: UNMutableNotificationContent?

    override func didReceive(_ request: UNNotificationRequest, withContentHandler contentHandler: @escaping (UNNotificationContent) -> Void) {
        self.contentHandler = contentHandler
        bestAttemptContent = (request.content.mutableCopy() as? UNMutableNotificationContent)

        if let bestAttemptContent = bestAttemptContent {
            handleContent(bestAttemptContent: bestAttemptContent)

            contentHandler(bestAttemptContent)
        }
    }

    override func serviceExtensionTimeWillExpire() {
        if let contentHandler = contentHandler, let bestAttemptContent =  bestAttemptContent {
            handleContent(bestAttemptContent: bestAttemptContent)

            contentHandler(bestAttemptContent)
        }
    }

    func handleContent(bestAttemptContent: UNMutableNotificationContent) {
        if let data = bestAttemptContent.userInfo as? [String: Any], let aps = bestAttemptContent.userInfo["aps"] as? [String: Any], let alert = aps["alert"] as? [String: Any] {
            if let locKey = alert["loc-key"] as? String, let locArgs = alert["loc-args"] as? [String] { 
                bestAttemptContent.body = //Uptaded notification text
            }
        }
    }
}

答案 1 :(得分:0)

您可以像这样简单地在dictionary中添加自定义键,

{
    "aps" : {
        "alert" : {
            "loc-key" : "localized_pn_text",
            "loc-args" : [ "France", "Frank"]
        },
        "sound" : "chime.aiff"
    },
    "acme" : "foo",
    "customText": "Frank, you got a push notification"
}

使用读取customText的值,

if let customText = notification.request.content.userInfo["customText"] as? String {
    print(customText)
}

答案 2 :(得分:0)

实际上,您可以使用%<parameter index starting with 1>$@

选择参数

例如,我可以将其写在Localizable.strings文件中: "localized_pn_text" = "%2$@, you got a push notification"