Solved

Localization issue, duration always returned in english

  • 23 July 2021
  • 3 replies
  • 643 views

Badge +3

We’re trying to display the duration of a subscription using Swift and the IOS SDK but the locale isn’t honored and the duration is always return in english, e.g. “1 Year” instead of “1 Jahr” for german with “de” locale. Does anyone have the same issue?

We’re trying to access the localized duration like so:

package.product.subscriptionPeriod?.durationTitle.localizedLowercase

Any tipps?

icon

Best answer by cody 23 July 2021, 17:05

View original

3 replies

Userlevel 6
Badge +8

Hey @etrality! Thanks for the clarification, I just tested this and it seems to work:

If you modify the `format` method from that Stack Overflow post to include a specific locale for the calendar, this translation will work as expected. Here’s my new `format` method I’m using:

    static func format(unit: NSCalendar.Unit, numberOfUnits: Int) -> String? {
var calendar = Calendar.current
calendar.locale = Locale.current // to test German: Locale(identifier: "de")

var dateComponents = DateComponents()
dateComponents.calendar = calendar
componentFormatter.allowedUnits = [unit]
switch unit {
case .day:
dateComponents.setValue(numberOfUnits, for: .day)
case .weekOfMonth:
dateComponents.setValue(numberOfUnits, for: .weekOfMonth)
case .month:
dateComponents.setValue(numberOfUnits, for: .month)
case .year:
dateComponents.setValue(numberOfUnits, for: .year)
default:
return nil
}

return componentFormatter.string(from: dateComponents)
}

When I print the period method like this:

print(package.product.subscriptionPeriod?.localizedPeriod())

An Optional was printed to the console:

1 Jahr

 

Let me know if that works for you, too!

Badge +3

@cody Thanks Cody! If I understand it correctly this handles localization, meaning the formatting of time and pricing. What about the translation of human readable intervals like week, year, etc. into a different language?  

Userlevel 6
Badge +8

Hey @etrality!

It looks like maybe you’re referencing this method from our sample app, durationTitle. This is just meant to be an example of how you might format your durations for display in your app, but doesn’t provide any localization.

A more robust way to localize this information would be to use a date formatter, as referenced in this Stack Overflow post. Essentially, that answer provides an example extension of how you might convert SKProductSubscriptionPeriod units to localized titles to display in your paywall.

Reply