goodwhale / AspirinShot

Painless App Store screenshots with SwiftUI, in Xcode
Other
129 stars 2 forks source link

LocalizedStringKey to String translations does not work #4

Closed roygroothulze closed 11 months ago

roygroothulze commented 11 months ago

I use the following extensions to parse the LocalizedStringKey to a string. (Found this online). This works if I change the app language but does not work when exporting the screenshots in the different languages. At the places where I can use the LocalizedStringKey everything works as expected.

I am using SwiftUI to develop the app. Is there any way to fix this?

The extensions I use (source: https://stackoverflow.com/questions/60841915/how-to-change-localizedstringkey-to-string-in-swiftui):

extension LocalizedStringKey {
    var stringKey: String? {
        Mirror(reflecting: self).children.first(where: { $0.label == "key" })?.value as? String
    }

    func toString(locale: Locale = .current) -> String {
        return .localizedString(for: self.stringKey ?? "", locale: locale)
    }
}

extension String {
    static func localizedString(for key: String,
                                locale: Locale = .current) -> String {

        let language = locale.languageCode
        let path = Bundle.main.path(forResource: language, ofType: "lproj")!
        let bundle = Bundle(path: path)!
        let localizedString = NSLocalizedString(key, bundle: bundle, comment: "")

        return localizedString
    }
}
sowenjub commented 11 months ago

I assume the reason it's not working is because you're calling .toString(). As a result, it uses the .current value which is given by the simulator and supersedes any environment value, which is very annoying but that's just the way the previews work.

Giving your views the environment locale explicitly should do the trick:

struct ContentView: View {
    @Environment(\.locale) private var locale

    var body: some View {
       Text(LocalizedStringKey("My text").toString(locale: locale))
    }
}
roygroothulze commented 11 months ago

Thanks for your help! I forgot about the fact that I am using a singleton where the string value of the LocalizedStringKey is stored. Now I used the locale environment to update the data.

sowenjub commented 11 months ago

You're welcome ☺️