我們有一個本地化的應用程序。荷蘭的許多用戶將他們的設備設置爲英語,並將其設爲荷蘭語的第二語言。我們的應用中有一個語言選擇菜單,因爲99.9%的用戶需要荷蘭交通信息而不是英語。因此,如果首選語言之一是荷蘭語,我們將該語言設置爲荷蘭語。UILocalNotification NSLocalizedString使用設備的語言
這個工程很好,除了UILocalNotifications和設備語言是英語(第二個是荷蘭語)。我們的應用程序語言是荷蘭語(但對於與系統語言不同的任何其他語言應該是相同的)。
這是我們如何將語言設置爲特定choosen語言,在這個例子中的荷蘭(通過使用回答這個線程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翻譯成系統語言(英語)而不是應用程序語言(荷蘭語),這似乎很奇怪。
蘋果的文件說的:
alertBody物業通知警報顯示該消息。使用 NSLocalizedString作爲消息的值。如果此 屬性的值非零,則會顯示警報。默認值爲零 (無警報)。顯示之前,將從 字符串中去除Printf樣式轉義字符;要在 消息中包含百分號(%),請使用兩個百分號(%%)。
iOS的決定如果一個本地化的字符串或只是一個字符串,沒有任何區別。
問題:當字符串存在於本地化文件中時,如何確保所有本地通知都使用選定的用戶語言(本例中爲荷蘭語)而不是系統語言?
解決方法(只需添加一個空格本地化的字符串):
localNotification.alertTitle = [NSString stringWithFormat:@"%@ ", NSLocalizedString(@"Some notifcation text", @"Notification text")];