1

我知道我们可以通过以下方法处理推送通知:

- (void)application:(UIApplication *)application didReceiveRemoteNotification:(NSDictionary *)userInfo

我们可以检查应用程序是否在前台运行:

if (application.applicationState == UIApplicationStateActive ) { ... }

我们如何通过本地化显示完全相同的通知?

NSString *message = [[[userInfo valueForKey:@"aps"] valueForKey:@"alert"] valueForKey:@"loc-key"];
NSString *trueMessage = NSLocalizedString(message, nil);
UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:@"Alert"
                                                            message:trueMessage
                                                   cancelButtonItem:@"OK"
                                                   otherButtonItems:@"Show", nil];
[alertView show];

这显示了未本地化的原始文本,例如“您在 %2@ 收到来自 %1@ 的新警报”。

loc-args我的问题是,当应用程序在前台运行时,我们如何将 UIAlertView 也放入其中?

4

2 回答 2

1

我想出了一个不那么简单的解决方法(假设 3 是您在所有本地化字符串中拥有的最大变量数):

    // Max is 3 variables
    NSString *variableOne = @"";
    NSString *variableTwo = @"";
    NSString *variableThree = @"";

    int i = 0;
    for (NSString *eachVariable in [[[userInfo valueForKey:@"aps"] valueForKey:@"alert"] valueForKey:@"loc-args"]) {
        switch (i) {
            case 0:
                variableOne = eachVariable;
                break;
            case 1:
                variableTwo = eachVariable;
                break;
            case 2:
                variableThree = eachVariable;

            default:
                break;
        }
        i++;
    }

    NSString *message = [[[userInfo valueForKey:@"aps"] valueForKey:@"alert"] valueForKey:@"loc-key"];

    NSString *trueMessage = [NSString stringWithFormat:NSLocalizedString(message, nil), variableOne, variableTwo, variableThree];

    UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:@"Alert"
                                                        message:trueMessage
                                               cancelButtonItem:@"Cancel"
                                               otherButtonItems:@"Show", nil];
    [alertView show];
于 2012-10-28T10:57:41.763 回答
1

我建议您va_list按照此处的说明创建一个假货:fake va_list in ARC

这将给出一个看起来有点像这样的代码:

NSString *pushBody;
id alert = userInfo[@"aps"][@"alert"];
if ([alert isKindOfClass:[NSString class]]) pushBody = alert;
if ([alert isKindOfClass:[NSDictionary class]])
{
    pushBody = alert[@"loc-key"];
    if (pushBody == nil)
    {
        pushBody = alert[@"body"];
    }
    else
    {
        // Build a fake va_list from the parameters.
        NSArray *locArgs = alert[@"loc-args"];
        NSRange range = NSMakeRange(0, [locArgs count]);
        NSMutableData* fakeVaList = [NSMutableData dataWithLength: sizeof(id) * [locArgs count]];
        [locArgs getObjects:(__unsafe_unretained id *)fakeVaList.mutableBytes range:range];

        pushBody = StrLoc(pushBody, @"Remote Notif");
        pushBody = [[NSString alloc] initWithFormat:pushBody arguments:fakeVaList.mutableBytes];
    }
}

告诉我这是否适合你……</p>

于 2013-10-17T15:05:44.327 回答