Skip to content

Commit

Permalink
feat: add support for changing languages without restarting app (#276)
Browse files Browse the repository at this point in the history
  • Loading branch information
guoyingtao committed Feb 5, 2023
1 parent 87fba7f commit 5227009
Show file tree
Hide file tree
Showing 3 changed files with 42 additions and 6 deletions.
12 changes: 7 additions & 5 deletions Sources/Mantis/Config.swift
Original file line number Diff line number Diff line change
Expand Up @@ -59,13 +59,15 @@ public struct Config {
guard let bundle = Bundle(identifier: bundleIdentifier) else {
return nil
}

if let url = bundle.url(forResource: "MantisResources", withExtension: "bundle") {
let bundle = Bundle(url: url)
return bundle

guard let url = bundle.url(forResource: "MantisResources", withExtension: "bundle") else {
return nil
}
return nil

return Bundle(url: url)
}()

static var language: Language?

public init() {}

Expand Down
20 changes: 19 additions & 1 deletion Sources/Mantis/Helpers/LocalizedHelper.swift
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,7 @@ import Foundation

struct LocalizedHelper {
private static var bundle: Bundle?

static func setBundle(_ bundle: Bundle) {
guard let resourceBundleURL = bundle.url(
forResource: "MantisResources", withExtension: "bundle")
Expand All @@ -28,6 +28,10 @@ struct LocalizedHelper {
#if MANTIS_SPM
let bundle = localizationConfig.bundle ?? Bundle.module

guard let bundle = convertToLanguageBundleIfNeeded(by: bundle) else {
return value
}

return NSLocalizedString(
key,
tableName: localizationConfig.tableName,
Expand All @@ -40,6 +44,10 @@ struct LocalizedHelper {
return value
}

guard let bundle = convertToLanguageBundleIfNeeded(by: bundle) else {
return value
}

return NSLocalizedString(
key,
tableName: localizationConfig.tableName,
Expand All @@ -49,4 +57,14 @@ struct LocalizedHelper {
)
#endif
}

static private func convertToLanguageBundleIfNeeded(by bundle: Bundle?) -> Bundle? {
if let languageCode = Mantis.Config.language?.code,
let languageBundlePath = bundle?.path(forResource: languageCode, ofType: "lproj"),
let languageBundle = Bundle(path: languageBundlePath) {
return languageBundle
}

return bundle
}
}
16 changes: 16 additions & 0 deletions Sources/Mantis/Mantis.swift
Original file line number Diff line number Diff line change
Expand Up @@ -60,6 +60,22 @@ public func crop(image: UIImage, by cropInfo: CropInfo) -> UIImage? {
return image.crop(by: cropInfo)
}

public struct Language {
var code: String

public init(code: String) {
self.code = code
}
}

public func chooseLanguage(_ language: Language) {
Mantis.Config.language = language
}

public func resetLanguage() {
Mantis.Config.language = nil
}

// MARK: - internal section
var localizationConfig = LocalizationConfig()

Expand Down

0 comments on commit 5227009

Please sign in to comment.