When you are developing an SDK. You need some extra operation.
1) create **Localizable.strings** as usual in YourLocalizeDemoSDK.
2) create the same **Localizable.strings** in YourLocalizeDemo.
3) find your **Bundle Path** of YourLocalizeDemoSDK.
**Swift4**:
// if you use NSLocalizeString in NSObject, you can use it like this
let value = NSLocalizedString("key", tableName: nil, bundle: Bundle(for: type(of: self)), value: "", comment: "")
`Bundle(for: type(of: self))` helps you to find the bundle in YourLocalizeDemoSDK. If you use `Bundle.main` instead, you will get a wrong value(in fact it will be the same string with the key).
But if you want to use the String extension mentioned by [dr OX][1]. You need to do some more. The origin extension looks like this.
extension String {
var localized: String {
return NSLocalizedString(self, tableName: nil, bundle: Bundle.main, value: "", comment: "")
}
}
As we know, we are developing an SDK, `Bundle.main` will get the bundle of YourLocalizeDemo's bundle. That's not what we want. We need the bundle in YourLocalizeDemoSDK. This is a trick to find it quickly.
Run the code below in a NSObject instance in YourLocalizeDemoSDK. And you will get the URL of YourLocalizeDemoSDK.
let bundleURLOfSDK = Bundle(for: type(of: self)).bundleURL
let mainBundleURL = Bundle.main.bundleURL
Print both of the two url, you will find that we can build bundleURLofSDK base on mainBundleURL. In this case, it will be:
let bundle = Bundle(url: Bundle.main.bundleURL.appendingPathComponent("Frameworks").appendingPathComponent("YourLocalizeDemoSDK.framework")) ?? Bundle.main
And the String extension will be:
extension String {
var localized: String {
let bundle = Bundle(url: Bundle.main.bundleURL.appendingPathComponent("Frameworks").appendingPathComponent("YourLocalizeDemoSDK.framework")) ?? Bundle.main
return NSLocalizedString(self, tableName: nil, bundle: bundle, value: "", comment: "")
}
}
Hope it helps.
[1]: https://stackoverflow.com/a/29384360/4789773
I use next solution:
1) create extension:
extension String {
var localized: String {
return NSLocalizedString(self, tableName: nil, bundle: Bundle.main, value: "", comment: "")
}
}
2) in **Localizable.strings** file:
"Hi" = "Привет";
3) example of use:
myLabel.text = "Hi".localized
enjoy! ;)
**--upd:--**
*for case with comments you can use this solution:*
1) Extension:
extension String {
func localized(withComment:String) -> String {
return NSLocalizedString(self, tableName: nil, bundle: Bundle.main, value: "", comment: withComment)
}
}
2) in .strings file:
/* with !!! */
"Hi" = "Привет!!!";
3) using:
myLabel.text = "Hi".localized(withComment: "with !!!")