为什么我的语言包路径在iOS Swift中返回nil?

时间:2018-02-12 06:56:13

标签: ios swift localization

所以我的字符串有一个扩展名。我在项目中使用简体中文和繁体中文。我试图为我的字符串手动切换语言,但我的

Bundle(path: URL(fileURLWithPath: bundlePath ?? "").deletingLastPathComponent().absoluteString)

总是返回nil。我在Xcode项目中有我的本地化字符串。有人可以帮忙吗?

 extension String {
    var localized: String {

        //zh-Hans.lproj
        let lang = UserDefaults.standard.string(forKey: "i18n_language")
        let bundlePath: String? = Bundle.main.path(forResource: "Localizable", ofType: "strings", inDirectory: nil, forLocalization: "zh-Hans")
        print("bundlePath = \(String(describing: bundlePath!))")
        // here i get path as bundlePath = /var/containers/Bundle/Application/C3xx3D-BxxC-4Dx3-xx8D-156xxxxxxx3D/xxxx.app/zh-Hans.lproj/Localizable.strings
        let langBundle = Bundle(path: URL(fileURLWithPath: bundlePath ?? "").deletingLastPathComponent().absoluteString)
        print("langBundle = \(langBundle)") // getting nil

        return NSLocalizedString(self, tableName: nil, bundle: langBundle!, value: "", comment: "")
    }
}

1 个答案:

答案 0 :(得分:0)

由于您没有将bundlePath转换为URL,因此您获得了nil。

在这一行:

let langBundle = Bundle(path: URL(fileURLWithPath: bundlePath ?? "").deletingLastPathComponent().absoluteString)

试试这样:

let langBundle = Bundle(path: URL(fileURLWithPath: "file://\(bundlePath)" ?? "").deletingLastPathComponent().absoluteString)

但是为什么要将字符串转换为URL然后再转换为字符串?你可以直接这样做:

let bundlePath: String? = Bundle.main.path(forResource: "Localizable", ofType: "strings", inDirectory: nil, forLocalization: "zh-Hans")
print("bundlePath = \(String(describing: bundlePath!))")
// here i get path as bundlePath = /var/containers/Bundle/Application/C3xx3D-BxxC-4Dx3-xx8D-156xxxxxxx3D/xxxx.app/zh-Hans.lproj/Localizable.strings

if let bundlePathString = bundlePath{
   let langBundle = Bundle.init(path: bundlePathString)
    print("langBundle = \(String(describing: langBundle))")
}