【问题标题】:Retrieving user defined values in Plist在 Plist 中检索用户定义的值
【发布时间】:2019-02-21 04:12:03
【问题描述】:

我正在尝试在我的 .plist 中检索用户定义的构建设置。 我正在开发一个 Mac 应用程序,我正在使用 Info.plist(不应该是自定义的,对吧?)

我使用以下代码从 Plist 中检索我的值:

func applicationDidFinishLaunching(_ aNotification: Notification) {
    // Insert code here to initialize your application
    let defaults = UserDefaults.standard
    defaults.set(nil, forKey: "access_token")
    defaults.set(nil, forKey: "refresh_token")
    self.userLoggedOut()

    let em = NSAppleEventManager.shared()
    em.setEventHandler(self, andSelector: #selector(self.getUrl(_:withReplyEvent:)), forEventClass: AEEventClass(kInternetEventClass), andEventID: AEEventID(kAEGetURL))

    var myDict: NSDictionary?
    if let path = Bundle.main.path(forResource: "Info", ofType: "plist") {
        myDict = NSDictionary(contentsOfFile: path)
        let serverURLString = myDict?.object(forKey: "SERVER_URL") as! String
        let appNameString = myDict?.object(forKey: "APP_NAME") as! String
        print(serverURLString)
        print(appNameString)
        Constant.apiUrlString = serverURLString
        Constant.applicationName = appNameString
    }
}

这将打印: $(YT_SERVER_URL) $(YT_APP_NAME)

我的 plist 如下所示:

我已在我的项目 > 目标中添加了用户定义的构建设置

为什么我找不到我在那里添加的值?我究竟做错了什么?

【问题讨论】:

  • myDict 返回什么?
  • @Rutger 检查解决方案。我想它会对你有所帮助。

标签: swift xcode macos


【解决方案1】:

首先,您可以从Plist 访问用户定义的值。要从Plist 访问用户定义的值,您需要添加以下代码:

extension Bundle {
    var apiBaseURL: String {
        return object(forInfoDictionaryKey: "serviceURL") as? String ?? ""
    }
}

用法:

let appConfiguration =  Bundle.main.apiBaseURL

您的applicationDidFinishLaunching 将如下所示:

func applicationDidFinishLaunching(_ aNotification: Notification) {
    let defaults = UserDefaults.standard
    defaults.set(nil, forKey: "access_token")
    defaults.set(nil, forKey: "refresh_token")
    self.userLoggedOut()

    let em = NSAppleEventManager.shared()
    em.setEventHandler(self, andSelector: #selector(self.getUrl(_:withReplyEvent:)), forEventClass: AEEventClass(kInternetEventClass), andEventID: AEEventID(kAEGetURL))

    Constant.apiUrlString = Bundle.main.apiBaseURL
    Constant.applicationName = Bundle.main.appName
}

除此之外,您还需要检查以下事项

  1. 转到包装并检查Info Plist 文件。它必须是您的主要 Info Plist 文件。

  2. 检查 Info Plist 您如何在 Info Plist 文件中获取用户定义的值

【讨论】:

  • 我在我的一个项目中做过类似的事情,效果很好!!!
  • 我检查了你的设置和我的项目,除了变量名不同之外,它都是一样的。仍然没有工作......然后我决定删除所有变量并使用您拥有的完全相同的名称/设置重新执行所有操作。有用!谢谢贾维斯
【解决方案2】:

使用这些行,您可以获得 Plist 字典 ::

guard let path = Bundle(for: *YourClass*.self).url(forResource: "Info", withExtension: "plist"),
      let dict = NSDictionary(contentsOf: path) as? [String: Any]
else {
    return 
}
// Access any key here like :: 
let serverUrl = dict["SERVER_URL"] as? String

【讨论】:

    猜你喜欢
    • 2013-10-08
    • 1970-01-01
    • 2021-07-31
    • 2016-03-08
    • 1970-01-01
    • 1970-01-01
    • 2014-11-18
    • 2020-03-17
    • 1970-01-01
    相关资源
    最近更新 更多