如何在 iOS 推送通知中合并 loc-args 和 loc-key 字符串

How to merge loc-args with loc-key string in iOS Push notification

我想在我的应用程序打开时将来自推送通知负载的 loc-args 数组的第二个元素设置为 loc-key 转换,例如在 didReceiveRemoteNotification 方法中。

有效负载中的 loc-args 示例是两个元素的数组:

[
    "Apple",
    "1 Infinite Loop Cupertino, CA 95014"
]

loc-key 的翻译是:

Goto address: %2$@

如果推送消息在应用程序处于后台时到达,则它可以正常工作。消息显示为:

Goto address: 1 Infinite Loop Cupertino, CA 95014

但是如果应用程序在前台,我必须在 didReceiveRemoteNotification 方法中自己处理它,例如:

let message = String(format: "Goto address: %2$@",
                     arguments: ["Apple", "1 Infinite Loop Cupertino, CA 95014"])

但这给出了结果:Goto address: Apple 而不是 Goto address: 1 Infinite Loop Cupertino, CA 95014

谁能告诉我如何解决这个问题?

额外信息:

如果我将 loc-key 更改为:Goto address: %2$@ - %1$@ 文本将是:Goto address: 1 Infinite Loop Cupertino, CA 95014 - Apple

谢谢。

你只有一个“@”,所以字符串只得到 "apple"。我认为当两个都得到时这个位置会起作用

在更好的解决方案之前,我执行以下 for 循环:

//grab the loc key
var messageText = NSLocalizedString(locKey, comment: "Key for the alert message")

//we need to merge the loc-args into the currentText
if let locArgs:NSArray = alert["loc-args"] as? NSArray {
    for (index, _) in locArgs.enumerate() {
        messageText = messageText.stringByReplacingOccurrencesOfString("%\(index+1)$@", withString: locArgs[index] as! String)
    }
}

这里有一个从 Swift 代码到 Obj-C

的分支
NSString *message = NSLocalizedString(locKey);
NSString *format = @"";
for (int i=0; i<[args count]; i++) {
    format = [NSString stringWithFormat:@"%%%d$@", i+1];
    message = [message stringByReplacingOccurrencesOfString:format withString:args[i]];
}