Giter Site home page Giter Site logo

decybel07 / l10n-swift Goto Github PK

View Code? Open in Web Editor NEW
314.0 5.0 32.0 10.86 MB

Localization of the application with ability to change language "on the fly" and support for plural form in any language.

License: MIT License

Swift 96.57% Ruby 2.21% C 1.21%
l10n localization localized language language-detection change-language pluralization plurals plural-form stringsdict

l10n-swift's Introduction

L10n-swift

Build Status CocoaPods Version Language Swift4 CocoaPods License Pod method Compatible Mentioned in Awesome-swift

L10n-swift is a simple framework that improves localization in swift app, providing cleaner syntax and in-app language switching.

Overview

Change language Simple translator Plurals

๐ŸŒŸ Features

  • Change the language of your apps "on the fly".
  • IBInspectable for Xcode Interface Builder (Cocoa - coming soon).
  • Support for user-defined Localizable file names.
  • Support for formats: *.plist, *.json, *.stringsdict, *.strings.
  • Support for grouping localization keys.
  • Support for plural forms in any language with multiple arguments.
  • Support for pseudo-languages: NonLocalized, DoubleLength, Accented, Bounded, ForcedRightToLeft.
  • Use .l10n() to localize any string, date and numbers.
  • Use more than one language at the same time.
  • About 25 times faster than a native solution.

๐Ÿ’ป Demo

pod try L10n-swift

โš ๏ธ Requirements

  • iOS 9.0+ | macOS 10.10+ | tvOS 9.0+ | watchOS 2.0+
  • Swift 4.0+

๐Ÿ‘ฅ Communication

  • If you found a bug, open an issue.
  • If you have a feature request, open an issue.
  • If you want to contribute, submit a pull request.

๐Ÿ“— Installation

Core Extension IBInspectable
L10n-swift โœ”๏ธ โœ”๏ธ โœ”๏ธ
L10n-swift/Core โœ”๏ธ
L10n-swift/Extension โœ”๏ธ โœ”๏ธ
L10n-swift/IBInspectable โœ”๏ธ โœ”๏ธ
pod 'L10n-swift', '~> 5.10'
github "Decybel07/L10n-swift", ~> 5.10
.Package(url: "https://github.com/Decybel07/L10n-swift.git", majorVersion: 5)

๐Ÿ“˜ Usage

Import L10n_swift at the top of each Swift file that will use framework.

import L10n_swift

Get localized text

Add .l10() following any String object you want localized:

"hello.world".l10n()

Get localized number

Add .l10() following number you want localized. Using the number format for the current language:

12.l10n()
24.l10n(minIntegerDigits: 4)
1.61803.l10n()
2.71828.l10n(fractionDigits: 2)

3.14.l10n { formatter in
    formatter.numberStyle = .currency
}

Get localized date

Add .l10() following any Date object you want localized using the date format for the current language:

Date().l10n()

Date().l10n { formatter in
    formatter.dateStyle = .medium
}

Get plural

Add .l10nPlural(CVarArg...) following any String object you want translated with plurals:

"numberOfApples".l10nPlural(2)

More about plurals, you can read on wiki

Observe language changed

Add observer for notification L10nLanguageChanged. This notification is called when language has been changed.

NotificationCenter.default.addObserver(
    self, selector: #selector(self.yourFunction), name: .L10nLanguageChanged, object: nil
)

Set language

L10n.shared.language = "en"
L10n.shared.language = "en-GB"

At runtime, you can switch the language at any time by setting the language property.

Get current language

L10n.shared.language

Get locale for current language

L10n.shared.locale

Get list of supported languages

L10n.supportedLanguages

A list of all the languages contained in the main bundle.

Get preferred language

L10n.preferredLanguage

A preferred language contained in the main bundle.

Supported formats

.plist, .stringsdict

Sample .plist and .stringsdict file

More about .plist format you can read on wiki.

More about .stringsdict format you can read on wiki.

.json

Sample .json file

More about .json format you can read on wiki.

.strings

Sample .strings file

More about .strings format you can read on wiki.

๐Ÿ“™ FAQ

๐Ÿค“ Author

Adrian Bobrowski (Decybel07), [email protected]

๐Ÿ”‘ License

L10n-swift is available under the MIT license. See the LICENSE file for more info.

l10n-swift's People

Contributors

decybel07 avatar glassipbel avatar michalsrutek avatar shtnkgm avatar wsb9 avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar

l10n-swift's Issues

Language change on macOS doesn't update system menubar items

Short description of the issue.

System (default) menubar items don't update after a language change

What did you expect to happen?

Menubar adapts to new language selected

What happened instead?

Menubar didn't adapt to new language

How to reproduces this problem?

  1. Start app
  2. Take note of the menubar
  3. Change language
  4. See no changes

Environment

UI framework: SwiftUI
System: macOS Ventura 13.0

DebugDescription

L10n {
	Language: uk
	Preferred language: en
	Supported languages: ["en", "uk", "ru"]
	Bundles: [
		"/Users/egoryakovenko/Library/Developer/Xcode/DerivedData/Moc-cmqpfvhdudhbgibqasempmgnurue/Build/Products/Debug/Moc.app/Contents/Resources/uk.lproj",
		"/Users/egoryakovenko/Library/Developer/Xcode/DerivedData/Moc-cmqpfvhdudhbgibqasempmgnurue/Build/Products/Debug/Moc.app/Contents/Resources/en.lproj"
	]
}

(bundles change time to time, sometimes i have uk, sometimes i don't)

L10n-swift version: 5.10.2

Xcode version: Xcode 14.1 Build version 14B47 xcodebuild -version

Swift version: swift-driver version: 1.62.15 Apple Swift version 5.7.1 (swiftlang-5.7.1.135.2 clang-1400.0.29.51) Target: x86_64-apple-macosx13.0 swift -version

Platform(s):

  • iOS
  • watchOS
  • tvOS
  • macOS

File format(s):

  • strings
  • stringsdict
  • plist
  • json

Installation method:

  • CocoaPods
  • Carthage
  • Swift Package Manager
  • Other (which ones)

ios widget extension not working

Short description of the issue.

ios widget extension not working

What did you expect to happen?

widget language will change when app change language

What happened instead?

when I use L10n.shared.language = "en" , app have changed.
widget still maintaining the original language when search L10n.shared.language.

How to reproduces this problem?

Environment.

DebugDescription

**L10n-swift version: 5.10

Xcode version: Enter here xcodebuild -version

Swift version: Enter here swift -version

Platform(s):

  • [โœ“] iOS
  • watchOS
  • tvOS
  • macOS

File format(s):

  • [โœ“] strings
  • stringsdict
  • plist
  • json

Installation method:

  • [โœ“] CocoaPods
  • Carthage
  • Swift Package Manager
  • Other (which ones)

String.L10n() is not working

I added a Localizable.strings with 3 languages into project and included it in build phase.
This is english version of it:

/*
 strings.strings
 NavigationDrawerController
 
 Created by A.V.Ebrahimi on 4/21/17.
 Copyright ยฉ 2017 CosmicMind. All rights reserved.
 */
"AppName" = "Mallowin";

But now this is not working :
toolbar.title="AppName".l10n()

Info.plist localization support

Decybel07, thank you for sharing this awesome resource. Integration in Swift project is easy and well documented and it works perfectly well.

Only one issue remains from my perspective - either the Info.plist localication is not well documented or localization for Info.plist is not supported.

Would you pls comment on how to get this working?

Get compilation error "Cannot convert value of type 'Int' to expected argument type 'L10n'"

Short description of the issue.

I get this build error (but only on one machine):

image

On a different machine, the identical code does not error and works just as expected.

The SupportConnectionError is defined thus:

image

I found that on the machine on which the error is occurring, the Pods/Manifest.lock has got a different version for L10n-swift (the one without the error has 5.7.3) :

image

Has there been a change between these two versions which would cause this error to occur?

What did you expect to happen?

I expect it to build as expected without the error. Honestly I'm a bit stuck - I'm not really an expert on Swift, but it baffles me why this error is appearing only on one machine. Any ideas that can help would be appreciated.

How to reproduces this problem?

It is hard to say. Like I said it only seems to happen on one particular machine.

Environment.

The environment should be basically the same. Both are using xCode 14.2, and the code is built from the same source.

DebugDescription

Happy to do so if required? But since it is a build error, I don't know it would be relevant

L10n-swift version: 5.7.3 (works) 5.9.0 (errors)

Xcode version:

โฏ xcodebuild -version
Xcode 14.2
Build version 14C1

Swift version:

โฏ swift -version
swift-driver version: 1.62.15 Apple Swift version 5.7.2 (swiftlang-5.7.2.135.5 clang-1400.0.29.51)
Target: x86_64-apple-macosx12.

Platform(s):

  • iOS
  • watchOS
  • tvOS
  • macOS

File format(s):

  • strings
  • stringsdict
  • plist
  • json

Installation method:

  • CocoaPods
  • Carthage
  • Swift Package Manager
  • Other (which ones)

Plurals does not work

Short description of the issue.

Hi, I am using iOS 15. Tried both SPM and Pods. Firstly created "minutes_time.one" and "minutes_time.other" in Localizable.string in en.lproj. When I am trying to call "minutes_time".l10nPlural(1) there is an error No exact matches in call to instance method 'l10nPlural'. Then I've tried to do "minutes_time".l10nPlural(args: [1]), but then I've got "minutes_time.other" version instead of "minutes_time.one"

Environment.

DebugDescription

L10n {
	Language: en
	Preferred language: en
	Supported languages: ["en"]
	Bundles: [
		"/var/containers/Bundle/Application/6353C86E-3F14-4D72-95DE-250F4628A4D1/.../en.lproj"
	]
}

L10n-swift version: 5.10

Xcode version: 13.2.1 xcodebuild -version

Swift version: 5.5.2 swift -version

Platform(s):

  • iOS
  • watchOS
  • tvOS
  • macOS

File format(s):

  • strings
  • stringsdict
  • plist
  • json

Installation method:

  • CocoaPods
  • Carthage
  • Swift Package Manager
  • Other (which ones)

Not support Localization in custom Framework

It works on Japanese and Italian perfectly (without needs to restart the app). But it did not works on Arabic and French even after restarting the app it not works. Kindly help me.

Conformance with CVarArg

Hi,

First of all, thanks for this library. Of all the projects I checked this one seems to handle plurals and localizations the best. I guess it takes handling plurals in Polish to understand this pain :P

I have some problems with String extension function. I try to call it as it is in examples:

"view_edit_profile_photos_content_text".l10n(args: 10)

For some reason XCode gives me following compile time exception:

Cannot invoke 'l10n' with an argument list of '(args: Int)'

Language doesn't change in static variables.

I have some static variables in a struct which are used to display error messages to users

struct AlertBody {

    static let SOMETHING_WRONG = "There was an error service in your request. Please try again from while".l10n()
    static let NO_NETWORK_ERROR = "No internet Connection found. Check your connection or try again.".l10n()
}

When I change the language, these static variables still give the message in previous language.
In order to get the messages in correct language I have to close and reopen the app.
But is there any other way to reload these static variables at the run time?

Too long localization keys problem

Hey
I found some interesting issue. Sometimes if key is too long and library don't find a proper translation in .plist app immediately shoots optional instead a key. Its generated by method "stringFromDictionary" in L10nResource. I suggest to use Swift version of Dictionary ;).

fails to install with swift pm

Short description of the issue.

Swift PM fails to resolve the dependency to L10n-swift

What did you expect to happen?

It should install just like it does with other libraries. (example: Alamofire, PinLayout)

What happened instead?

The dependency does not get resolved and swift package aborts with an error.

How to reproduces this problem?

Package.swift

// swift-tools-version:5.0
import PackageDescription

let package = Package(
    name: "Test",
    products: [],
    dependencies: [
        .package(url: "https://github.com/Decybel07/L10n-swift.git", .upToNextMajor(from: "5.5.1")),
    ],
    targets: [
        .target(
            name: "Test",
            dependencies: [
                "L10n-swift",
            ],
            path: "Test"
        ),
    ]
)

$ swift package resolve
Updating https://github.com/Decybel07/L10n-swift.git
error: dependency graph is unresolvable; found these conflicting requirements:

Dependencies: 
    https://github.com/Decybel07/L10n-swift.git @ 5.5.1..<6.0.0

Environment.

L10n-swift version: 5.5.1

Xcode version: Xcode 10.3, Build version 10G8

Swift version: Apple Swift version 5.0.1 (swiftlang-1001.0.82.4 clang-1001.0.46.5)

Platform(s):

  • iOS
  • watchOS
  • tvOS
  • macOS

Installation method:

  • CocoaPods
  • Carthage
  • Swift Package Manager
  • Other (which ones)

Storyboard localization

In the last version (4.1.1) of library option of localization in storyboard stopped working. Check this issue plz.

Wrong result/missing support for multiple arguments in plural function

Hi guys,
I would to use this lib but I had found there is not support for multiple arguments with plurals right?

For example, this is the value in Localizable.strings:

"__id_runs" = "%d runs";

and and Localizable.stringsdict:

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<dict>
	<key>NSStringLocalizedFormatKey</key>
	<string>%1$#@lu_completed_runs@</string>
	<key>lu_completed_runs</key>
	<dict>
		<key>NSStringFormatSpecTypeKey</key>
		<string>NSStringPluralRuleType</string>
		<key>NSStringFormatValueTypeKey</key>
		<string>lu</string>
		<key>zero</key>
		<string>No runs completed yet</string>
		<key>one</key>
		<string>One %2$#@lu_total_runs@</string>
		<key>other</key>
		<string>%lu %2$#@lu_total_runs@</string>
	</dict>
	<key>lu_total_runs</key>
	<dict>
		<key>NSStringFormatSpecTypeKey</key>
		<string>NSStringPluralRuleType</string>
		<key>NSStringFormatValueTypeKey</key>
		<string>lu</string>
		<key>one</key>
		<string>run completed</string>
		<key>other</key>
		<string>of %lu runs completed</string>
	</dict>
</dict>
</plist>

This is the native call to use it:

let completedRuns = 1
let totalRuns = 2
let format = NSLocalizedString("__id_runs", comment: "")
let translatedString = String(format: format, completedRuns, totalRuns)

The result is correct: One of 2 runs completed

The same operation with L10n-swift ends with a wrong result because I can pass just one value as arg parameter for plural() function

let value = l10n.plural(for: "__id_runs", resource: nil, fittingWidth: nil, arg: 1, converting: { $0 })

which results in a wrong string: One %2$#@lu_total_runs@

AppleLanguages isn't updated in some conditions, leading to Apple UI Stock elements to show in the wrong language

Short description of the issue.

I guess there is an issue in the preferredLanguage setter in Bundle+utils.swift where the AppleLanguages user default is not updated correctly if the preferred language is already the first item in the preferred languages list. It can happen if I set L10n.shared.language to another language than my preferredLanguage, then set it back to the preferredLanguage. This issue leads to Apple UI Stock elements to show in the wrong language (for example, an image picker).

What did you expect to happen?

The AppleLanguages user default should be updated correctly, even if the new value is already the first item in the preferred languages list.

What happened instead?

When setting preferredLanguage to a value that is already the first item in the list, the method returns early and does not update the AppleLanguages user default. This results in the previous language to remain first in the list.

How to reproduce this problem?

  1. Initial preferredLanguages as defined in my project is ["fr"]
  2. Call preferredLanguage = "en" (by setting L10n.shared.language = "en")
  3. AppleLanguages now contains ["en", "fr"]
  4. Call preferredLanguage = "fr" (by setting L10n.shared.language = "fr")
  5. AppleLanguages still contains ["en", "fr"] because it hasn't been updated, whereas it should only contain ["fr"].
  6. Notice that Apple UI Stock elements are showing up in English whereas they should show up in French.

Suggested fix

I've fixed it by replacing this check:

guard index > 0 else {
    return
}

to this:

guard index >= 0 else {
    return
}

Thanks to this, it doesn't return early and thus doesn't prevent AppleLanguages from being updated.

IBInspectable with custom bundle

I use L10n-swift library for the project localization.

My project receives localisation files from the backend as json and stores it to the separate bundle in project's Documents folder.

And I have to load localizations from Documents to L10n.

I know that L10n can be created as a new instance and pass my bundle as parameter into init method, but IBInspectable extension won't work with the custom bundle, bcouz IBInspectable use shared singleton with default L10n initialization.

How can I load my Bundle to L10n.shared and use IBInspectable extension as Main bundle?

Line break are escaped in translated strings

With the string Phone\nNumber in the .stringsdict, I'm getting the following string "Phone\\nNumber" instead of "Phone\nNumber".

Environment.

DebugDescription

"L10n {\n\tLanguage: en\n\tPreferred language: en\n\tSupported languages: [\"en\"]\n\tBundles: [\n\t\t\"/var/containers/Bundle/Application/1E0B4F9F-2F20-4503-8108-2C06E1FEDBE7/Cruise.app/en.lproj\",\n\t\t\"/var/containers/Bundle/Application/1E0B4F9F-2F20-4503-8108-2C06E1FEDBE7/Cruise.app/Base.lproj\"\n\t]\n}"

L10n-swift version:
5.7.3

Xcode version:
Xcode 12.4
Build version 12D4e

Swift version:
Apple Swift version 5.3.2 (swiftlang-1200.0.45 clang-1200.0.32.28)
Target: x86_64-apple-darwin19.6.0

Platform(s):

  • iOS
  • watchOS
  • tvOS
  • macOS

File format(s):

  • strings
  • stringsdict
  • plist
  • json

Installation method:

  • CocoaPods
  • Carthage
  • Swift Package Manager
  • Other (which ones)

SwiftUI Support

Is your feature request related to a problem? Please describe.
Nope

Describe the solution you'd like
Port for SwiftUI

Describe alternatives you've considered
N/A

Additional context

tried with this but doesnt work..

@State var currLang = L10n.shared.language

let langChanged = NotificationCenter.default
    .publisher(for: .L10nLanguageChanged)
    .makeConnectable()
    .autoconnect()

VStack{}
    .onReceive(langChanged) { _ in
        self.currLang = L10n.shared.language
    }

Plural localization not working

Just installed this pod and tried plural localization via
"eventCount".l10n(arg: count)
Added this lines to Localizable.strings

"eventCount.one" = "%d event";
"eventCount.many" = "%d events";
"eventCount.other" = "%d events";

Traced code, self.bundle in this function is nil, so no resource is loaded

    private func resource(named resourceName: String?) -> ResourceContainer {
        let resourceName = (resourceName ?? "").isEmpty ? "Localizable" : resourceName!

        return self.resources[resourceName] ?? {
            let resource = ResourceContainer(bundle: self.bundle, name: resourceName)
            self.resources[resourceName] = resource
            return resource
        }()
    }

Version 5.1.0

Swift 5.0 Support

Can you update the library to Swift 5.0?

Let me know if you need help i could create PR and do it myself :)

language not changing in storyboard

Short description of the issue.

I have two Issues:

  1. While I am changing app language it is not changing language of storyboard. It only changes string which is hard coded in code.
  2. While I Re-Run app it runs with default language not with previously selected language

What did you expect to happen?

  • Change language in storyboard
  • Set language selected unless user select other language

What happened instead?

  • It changes language which is hard coded in code("Ok".l10n()) not changing in storyboard. - Language changes to default language every time I rerun app

How to reproduces this problem?

Here what I am doing for changing language:
L10n.shared.language = "fr"
After L10nLanguageChanged notification fired I am relaunching storyboard

let delegate = (UIApplication.shared.delegate! as! AppDelegate)
let storyboard = UIStoryboard(name: "Main", bundle: nil)
delegate.window!.rootViewController! = storyboard.instantiateInitialViewController()!

Environment.

DebugDescription

{
	Language: fr
	Preferred language: en
	Supported languages: ["en", "fr", "pt-PT", "sw"]
	Bundles: [
		"/var/containers/Bundle/Application/E88839BF-E6FA-439F-A73A-F52B1A59DDBD/MyApp.app/fr.lproj",
		"/var/containers/Bundle/Application/E88839BF-E6FA-439F-A73A-F52B1A59DDBD/MyApp.app/Base.lproj"
	]
}

L10n-swift version: Swift 4.2

Xcode version: Xcode 10.2.1

Swift version: Swift 5

Platform(s):

  • iOS

File format(s):

  • strings

Installation method:

  • CocoaPods

Note:
I have localized storyboard with other languages.

/* Class = "UILabel"; text = "Home"; ObjectID = "7D7-TL-I6S"; */
"7D7-TL-I6S.text" = "Accueil";

If I add text in L10n Text in Attributes inspector language changes works in storyboard.
Can I change language without assigning text (L10n Text) to every control? I have localized every text in Main.strings(French) for storyboard.

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.