首页 文章

UILocalNotification NSLocalizedString使用设备语言

提问于
浏览
3

我们有一个本地化的应用荷兰的很多用户将他们的设备设置为英语,并将其设置为荷兰语的第二语言 . 我们的应用程序中有一个语言选择菜单,因为99.9%的用户想要荷兰的交通信息,而不是英语 . 因此,如果首选语言之一是荷兰语,我们将语言设置为荷兰语 .

除了UILocalNotifications之外,它的效果很好,设备语言是英语(第二个是荷兰语) . 我们的应用程序语言是荷兰语(但对于与系统语言不同的任何其他语言应该是相同的) .

这是我们如何将语言设置为特定的选择语言,在此示例中为荷兰语(通过使用此线程的答案How to force NSLocalizedString to use a specific language):

[[NSUserDefaults standardUserDefaults] setObject:[NSArray arrayWithObjects:language, nil] forKey:@"AppleLanguages"];
[[NSUserDefaults standardUserDefaults] synchronize]; //to make the change immediate

这是我们发送UILocalNotification的方式:

UILocalNotification* localNotification = [[UILocalNotification alloc] init];

localNotification.alertBody = message;
if(notificationCategory != NULL)
    localNotification.category = notificationCategory;
if(referenceDic != NULL)
    localNotification.userInfo = referenceDic;

if(title != nil && [localNotification respondsToSelector:@selector(setAlertTitle:)])
{
    [localNotification setAlertTitle:title];
}
[[UIApplication sharedApplication] presentLocalNotificationNow:localNotification];

NSString var *消息是LocalizedString,在调试时,此字符串是荷兰语:

(lldb) po localNotification
 <UIConcreteLocalNotification: 0x15ce32580>{fire date = (null), time zone = (null), repeat interval = 0, repeat count = UILocalNotificationInfiniteRepeatCount, next fire date = Wednesday 14 October 2015 at 09 h 56 min 47 s Central European Summer Time, user info = (null)}

 (lldb) po localNotification.alertBody
 Flitsmeister heeft geconstateerd dat je niet meer onderweg bent en is automatisch uitgeschakeld.

 (lldb) po localNotification.alertTitle
 nil

现在iOS收到此localNotification并尝试将其翻译为英语 . 此转换有效,因为字符串位于本地化文件中 .

如果消息不在翻译文件中(因为它中有一个数字)或者如果我在消息的末尾添加一个空格,它将在本地化文件中找不到该字符串并显示荷兰语通知 .

iOS尝试将LocalNotification转换为系统语言(英语)而不是应用程序语言(荷兰语)似乎很奇怪 .

Apple的文档说明了这一点:

alertBody属性通知警报中显示的消息 . 分配一个字符串,或者最好是一个本地化字符串键(使用NSLocalizedString)作为消息的值 . 如果此属性的值为非零,则会显示警报 . 默认值为nil(无警报) . 在显示之前从字符串中剥离Printf样式转义字符;要在邮件中包含百分号(%),请使用两个百分号(%%) .

https://developer.apple.com/library/ios/documentation/iPhone/Reference/UILocalNotification_Class/#//apple_ref/occ/instp/UILocalNotification/alertBody

iOS决定它是一个本地化的字符串还是只是一个字符串,没有区别 .

问题:当本地化文件中存在字符串时,如何确保所有本地通知都使用所选用户语言(本例中为荷兰语)而不是系统语言?

解决方法(只需向本地化字符串添加空格):

localNotification.alertTitle = [NSString stringWithFormat:@"%@ ", NSLocalizedString(@"Some notifcation text", @"Notification text")];

1 回答

  • 0

    谢谢,它解决了我的问题 . 使用 [NSString stringWithFormat:@"%@ " 真的有用!

    notifyAlarm.alertBody = [NSString stringWithFormat:@"%@ ", NSLocalizedString(@"some text here", nil)];
    

相关问题