ios - 基于应用程序语言而不是设备语言的本地化请求权限

标签 ios swift iphone localization

本地化在我的应用程序中运行良好。我想要本地化权限对话框短信。它可以很好地适应设备语言的更改,但我想根据我的应用程序语言更改消息。

我尝试过以下代码

import UIKit

class LocalizeHelper: NSObject {

    private var myBundle: Bundle? = nil

    static let shared: LocalizeHelper = {
        let instance = LocalizeHelper()
        return instance
    }()

    override init() {
        super.init()
        // use systems main bundle as default bundle
        myBundle = Bundle.main

    }

    func localizedString(forKey key: String) -> String {
        return myBundle!.localizedString(forKey: key, value: "", table: nil)
    }

    //  Converted with Swiftify v1.0.6331 - https://objectivec2swift.com/
    func setLanguage(_ lang: String) {
        // path to this languages bundle
        let path: String? = Bundle.main.path(forResource: lang, ofType: "lproj")
        if path == nil {
            // there is no bundle for that language
            // use main bundle instead
            myBundle = Bundle.main
        }
        else {
            // use this bundle as my bundle from now on:
            myBundle = Bundle(path: path!)
            // to be absolutely shure (this is probably unnecessary):
            if myBundle == nil {
                myBundle = Bundle.main
            }
        }
    }

    func getLanguage() -> String {
        print("\(String(describing: myBundle?.bundlePath.last))")
        //return myBundle!.bundlePath.last >> Error
        return myBundle!.bundlePath.lastCharacter!
    }
}

extension String {
    public var lastCharacter: String? {
        guard let aLast = self.last else {
            return nil
        }
        return String(aLast)
    }
}

enter image description here

我在 StackOverflow 上冲浪,但没有找到任何解决方案。我们感谢任何帮助外壳。

最佳答案

您最好的选择是将应用程序的语言保存在用户默认值中,例如作为字符串,然后当您将其从用户默认值中取出时,将其解析为自定义应用程序语言枚举。如果您没有保存任何应用程序语言,您始终可以使用设备语言,但更喜欢或使用用户默认值不为零的应用程序语言覆盖它。另外,最好您应该将用户默认交互与您在 View Controller 中访问的用户默认管理器进行包装。

因此建议的步骤是:

  • 创建用户默认管理器
  • 定义语言枚举
  • 实现setLanguage函数语言参数
  • 使用设备语言实现 getLanguage func 语言输出或 英语作为守卫返回

关于ios - 基于应用程序语言而不是设备语言的本地化请求权限,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57096679/

相关文章:

ios - Apple Pay 可以使用订阅支付模式吗?

ios - 你如何在 Swift 中锁定一个线程?

ios - 从 Xcode 将 Ad Hoc 应用程序安装到设备需要重启手机

iphone - 适用于所有 iOS (iPhone/iPad/Apple Watch) 设备的 App Store Connect 屏幕截图尺寸

ios - 一起使用 CGContextFillPath 和 CGContextStrokePath? iOS

ios - UISplitViewController,如何始终使用 UISplitViewControllerDisplayModePrimaryOverlay

iphone - 一个应用程序可以调用另一个应用程序然后返回结果吗?

iphone - "initialiser element is not a compile-time constant"创建 GCD 队列时

ios - 如何在 iPhone 中检查有效的 URL 模式?

objective-c - 未知类名 PKPaymentAuthorizationViewControllerDelegate