sha sha - 3 years ago 327
iOS Question

NSDateFormatter and current language in iOS11

It appears that default behavior for

has been changed in iOS11. This code used to work and produced date formatter according to currently selected iPhone/iPad language prior to iOS11:

_dateFormatterInstance = [[NSDateFormatter alloc] init];
_dateFormatterInstance.timeZone = [NSTimeZone systemTimeZone];

Looks like in iOS11 we have to explicitly specify locale property for it:

_dateFormatterInstance = [[NSDateFormatter alloc] init];
_dateFormatterInstance.timeZone = [NSTimeZone systemTimeZone];
_dateFormatterInstance.locale = [NSLocale localeWithLocaleIdentifier:[[NSLocale preferredLanguages] firstObject]];

Can somebody confirm my findings?

Answer Source

This isn't a problem with NSDateFormatter, it's a change in how iOS 11 supports localization.

Under iOS 11, [NSLocale currentLocale] only returns languages supported by your app's localizations. If your app only supports English (as the base localization), then no matter what language the user selects on the device, currentLocale will always return English.

Under iOS 10 and earlier, currentLocale would directly represent the user's chosen language and region, regardless of what localizations your app supports.

Classes such as NSDateFormatter default to using NSLocale currentLocale. So no matter what language your app actually supported through its localization, classes like NSDateFormatter would show text in the language set on the device, even it was different from the language being used by your app.

iOS 11 fixes this inconsistency. While one could argue that this change breaks lots of apps that only support one (or just a few) language, it actually makes the app more consistent.

To make all of this clear, consider an example. You create a simple test app with a base localization in English. If you run your app with iOS 10 and the device's language is set to English, you obviously see English text and you see dates formatted for English. If you now change the device's language to French and restart the app, the user now sees English text in the app (since that is its only localization) but dates now show with French month and weekday names.

Now run the same app under iOS 11. As with iOS 10, if the device's language is English you see everything in English. If you then change the device's language to French and run the app, iOS 11 sees that your app only supports English and currentLocale returns English, not French. So now the user sees English text (due to the app's localization) and dates are now also still in English.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download