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

时间:2016-03-10 12:12:39

标签: swift apple-push-notifications

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

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

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

loc键的翻译是:

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键更改为:Goto address: %2$@ - %1$@,则文字将为:Goto address: 1 Infinite Loop Cupertino, CA 95014 - Apple

感谢。

3 个答案:

答案 0 :(得分:1)

直到更好的解决方案,我执行以下循环:

#include <regex>
#include <string>
#include <iostream>
#include <vector>

#define isthirty(x) for (int i = 0; i < 3; i++) {if (days[i] == x[1]) {thirty = true;break;}}
using namespace std;

int main() {
    vector<string> words;
    string str;
    getline(cin, str);
    int N = stoi(str);
    int days[] = { 4,6,9,11 };
    regex exp1("[^a-zA-Z0-9]([1-9][0-9]{3}(?:-[0-9][1-9]){2})[^a-zA-Z0-9]");
    for (int i = 0; i < N; i++) {
        getline(cin, str);
        sregex_iterator it(str.cbegin(), str.cend(), exp1);
        sregex_iterator end;
        for (; it != end; it++) {
            words.push_back(it->str(0));
        }
    }

    regex exp2("([0-9])+");
    for (auto &it : words) {
        int dates[3] = {};
        sregex_iterator pos(it.cbegin(), it.cend(), exp2);
        sregex_iterator end;
        str = it.substr(1,10);
        for (int i = 0; pos != end; pos++, i++) {
            dates[i] = stoi(pos->str(0));
        }
        if (dates[0] > 2016 || dates[1] > 12 || dates[2] > 31) {
            continue;
        }
        bool thirty = false;
        isthirty(dates);
        if (thirty && dates[2] <= 30) {
            cout << str << "\n";
        }
        else if(dates[1] == 2) {
            if (dates[0] % 4 == 0 && dates[2] <= 29) {
                cout << str << "\n";
            }
            else if (dates[0] % 4 != 0 && dates[2] <= 28) {
                cout << str << "\n";
            }
        }
        else if (dates[2] <= 31) {
            cout << str << "\n";
        }
    }
    return 0;
}

答案 1 :(得分:0)

你只有一个“@”所以字符串只能得到“苹果”。我认为这个位置在两者都有效时会起作用

答案 2 :(得分:0)

这里有一个从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]];
}