1

I want to set the second element of the loc-args array from the push notification payload into the loc-key translation when my app is open, e.g. in the didReceiveRemoteNotification method.

Example of the loc-args in the payload is an array of two elements:

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

The translation for the loc-key is:

Goto address: %2$@

If the push message arrives when the app is in the background it works fine. The message is showed as:

Goto address: 1 Infinite Loop Cupertino, CA 95014

But if the app is in the foreground I have to handle it by myself in the didReceiveRemoteNotification method for example with:

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

But this gives the result: Goto address: Apple instead of Goto address: 1 Infinite Loop Cupertino, CA 95014

Can anyone tell me how to fix this?

Extra info:

If I change the loc-key to: Goto address: %2$@ - %1$@ the text will be: Goto address: 1 Infinite Loop Cupertino, CA 95014 - Apple

Thanks.

Melmer
  • 21
  • 5
  • `String(format:...)` does not allow to *omit* a positional parameter. See for example the comments in http://stackoverflow.com/questions/1063843/is-there-a-way-to-specify-argument-position-index-in-nsstring-stringwithformat . – Martin R Mar 10 '16 at 12:23

3 Answers3

1

Until a better solution I doing the following for loop:

//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)
    }
}
Melmer
  • 21
  • 5
0

you only have one "@" so string only get "apple".i think the position will work when both are gotten

Iniesta
  • 1
  • 1
0

Here you have a fork from your Swift code to 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]];
}
Sulfkain
  • 5,082
  • 1
  • 20
  • 38