1

我正在尝试在我的 .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 如下所示:

在此处输入图像描述

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

在此处输入图像描述

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

4

2 回答 2

2

首先,您可以从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 文件中获取用户定义的值

在此处输入图像描述 信息 Plist 文件

于 2019-02-21T04:41:47.837 回答
0

使用这些行,您可以获得 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
于 2019-02-21T05:04:50.467 回答