Files
purchases-ios/Sources/Paywalls/PaywallData+Localization.swift
T
Josh Holtz 1fa69d42f4 [Paywalls] Improve locale consistency (#4158)
⚠️ Waiting for #4188 to be merged first (because needs all the tests to
pass)

## Motivation

Fix cases where paywall was showing multiple languages at once and
random languages.

## Description

👉 For a demo of the problem and solution, look in Slack in the paywalls
or SDK channel for the latest Loom that I posted

### Flow of paywall localization logic (since it can be confusing)

1.
[PaywallView](https://github.com/RevenueCat/purchases-ios/pull/4158/files#diff-ea75fe7280803e15b975d702a16c6851ffc2bbed01b7b196bf0fb80d75b4b332)
starts with `Locale.current` but then calls
`offering.validatedPaywall()` which will return the new
`displayedLocale: Locale` variable
2.
[PaywallData+Validation](https://github.com/RevenueCat/purchases-ios/pull/4158/files#diff-452790cf5287a44f75a4b2260254db2281a066faeea2b3e441a007ec60522b6b)
returns `displayedLocale` if its a valid paywall, otherwise it return
`Locale.current` for fallback paywall
3.
[PaywallData+Localization](https://github.com/RevenueCat/purchases-ios/pull/4158/files#diff-e620baead94f7acad56d931c485d7691c4f909be3fe625e104528a2702cca2a0)
has a lot of the new logic
- New `locale: Locale` computer property that it determines the locale
from the `localizedConfiguration` or `localizedConfigurationsByTier`
- New ` defaultLocalizedConfiguration` that uses the developer set
`defaultLocale` (from `PaywallData`) to find the default localization
- Updated `localizedConfiguration<Value>()` to take a new
`defaultLocalization` to put in its priority (and log it if its used).
If for some reason that's not found, it will use the legacy
`fallbackLocalization` (which is the first localization it finds or
english)
4. After all of that, the `displayedLocale` is passed into the actually
SwiftUI `LoadedOfferingPaywallView` to show this locale everywhere

### Problem 1 - Inconsistent languages displayed at once

The user defined localizations and the pre-localized content in the SDK
(like links in the footer and package duration names) could should
different localizations. The choice of which locale was happening in two
different spots.

Since the SDK has all possible localizations that the dashboard offers,
the locale SDK displays from the dashboard will be chosen for the
pre-localized content.

### Problem 2 - Showing random languages if not supported

We decided early on to not use a `default_locale` but that has hurt us.
The solution to use was use `localizations.first` to show the first
locale in the list and the intention that this was the first locale the
user did in the paywall. That was not the case, however. The order of
the localizations list was indeterministic so it should should a random
language (even to the point where different random languages would show
the the same user).

We are now introducing a `default_locale` that the developer can set in
the paywall. If the locale the user is requesting is not translated by
the developer, it will use the `default_locale`

### Problem 3 - Footer not using correct localization from the bundle

There were times where some parts of the footer itself (mainly the
restore button) would be a different language than the terms of service
and privacy policy buttons. This was due to a code issue where we were
using `Bundle.module`. Instead, we needed to specify a localization
bundle specifically that we wanted to use.
2024-08-20 09:44:27 -05:00

152 lines
5.7 KiB
Swift

//
// Copyright RevenueCat Inc. All Rights Reserved.
//
// Licensed under the MIT License (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// https://opensource.org/licenses/MIT
//
// PaywallData+Localization.swift
//
// Created by Nacho Soto on 8/10/23.
import Foundation
public extension PaywallData {
/// - Returns: the `Locale` being used with ``PaywallData/LocalizedConfiguration-swift.struct``
var locale: Locale? {
let singleTier = self.localizedConfiguration(for: Self.localesOrderedByPriority)?.locale
let multiTier = self.localizedConfigurationByTier(for: Self.localesOrderedByPriority)?.locale
return singleTier ?? multiTier
}
/// - Returns: the ``PaywallData/LocalizedConfiguration-swift.struct`` to be used
/// based on `Locale.preferredLocales` or the default locale.
/// - Returns: `nil` for multi-tier paywalls.
var localizedConfiguration: LocalizedConfiguration? {
return self.localizedConfiguration(for: Self.localesOrderedByPriority)?.localizedConfiguration
}
/// - Returns: the ``PaywallData/LocalizedConfiguration-swift.struct`` to be used
/// based on `Locale.preferredLocales` or the default locale.
/// - Returns: `[:]` for single-tier paywalls.
var localizedConfigurationByTier: [String: LocalizedConfiguration]? {
return self.localizedConfigurationByTier(for: Self.localesOrderedByPriority)?.localizedConfiguration
}
// Visible for testing
internal func localizedConfiguration(
for preferredLocales: [Locale]
) -> (locale: Locale, localizedConfiguration: LocalizedConfiguration)? {
let defaultLocale = self.defaultLocale.map(Locale.init(identifier: ))
return Self.localizedConfiguration(
for: preferredLocales,
configForLocale: self.config(for:),
defaultLocalization: self.defaultLocalizedConfiguration(locale: defaultLocale),
fallbackLocalization: self.fallbackLocalizedConfiguration
)
}
// Visible for testing
internal func localizedConfigurationByTier(
for preferredLocales: [Locale]
) -> (locale: Locale, localizedConfiguration: [String: LocalizedConfiguration])? {
let defaultLocale = self.defaultLocale.map(Locale.init(identifier: ))
return Self.localizedConfiguration(
for: preferredLocales,
configForLocale: self.tiersLocalization(for:),
defaultLocalization: self.defaultTiersLocalized(locale: defaultLocale),
fallbackLocalization: self.fallbackTiersLocalized
)
}
// Visible for testing
/// - Returns: The list of locales that paywalls should try to search for.
/// Includes `Locale.preferredLanguages`.
internal static var localesOrderedByPriority: [Locale] {
// Removing the use of Locale.current as it should really only be used for dates, currency formatting, etc
return Locale.preferredLocales
}
private func defaultLocalizedConfiguration(locale: Locale?) -> (String, LocalizedConfiguration)? {
guard let locale else { return nil }
return self.localization.first { $0.0 == locale.identifier }
}
private func defaultTiersLocalized(locale: Locale?) -> (String, [String: LocalizedConfiguration])? {
guard let locale else { return nil }
return self.localizationByTier.first { $0.0 == locale.identifier }
}
private var fallbackLocalizedConfiguration: (String, LocalizedConfiguration)? {
return self.localization.first
}
private var fallbackTiersLocalized: (String, [String: LocalizedConfiguration])? {
return self.localizationByTier.first
}
}
// MARK: -
private extension PaywallData {
static func localizedConfiguration<Value>(
for preferredLocales: [Locale],
configForLocale: @escaping (Locale) -> Value?,
defaultLocalization: (locale: String, value: Value)?,
fallbackLocalization: (locale: String, value: Value)?
) -> (Locale, Value)? {
guard let (fallbackLocale, fallbackLocalization) = fallbackLocalization else {
Logger.debug(Strings.paywalls.empty_localization)
return nil
}
// Allows us to search each locale in order of priority, both with the region and without.
// Example: [en_UK, es_ES] => [en_UK, en, es_ES, es]
let locales: [Locale] = preferredLocales.flatMap { [$0, $0.removingRegion].compactMap { $0 } }
Logger.verbose(Strings.paywalls.looking_up_localization(preferred: preferredLocales,
search: locales))
let result: (locale: Locale, value: Value)? = locales
.lazy
.compactMap { locale in
configForLocale(locale)
.map { (locale, $0) }
}
.first { _ in true } // See https://github.com/apple/swift/issues/55374
if let result {
Logger.verbose(Strings.paywalls.found_localization(result.locale))
return result
} else if let (defaultLocale, defaultLocalization) = defaultLocalization {
Logger.warn(Strings.paywalls.default_localization(localeIdentifier: defaultLocale))
return (Locale(identifier: defaultLocale), defaultLocalization)
} else {
Logger.warn(Strings.paywalls.fallback_localization(localeIdentifier: fallbackLocale))
return (Locale(identifier: fallbackLocale), fallbackLocalization)
}
}
}
// MARK: -
extension Locale {
fileprivate static var preferredLocales: [Self] {
return Self.preferredLanguages.map(Locale.init(identifier:))
}
}