swift - 在 Plist 中检索用户定义的值

标签 swift xcode macos

我正在尝试在我的 .plist 中检索用户定义的build设置。 我正在开发 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 是这样的:

enter image description here

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

enter image description here

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

最佳答案

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

enter image description here Info Plist File

关于swift - 在 Plist 中检索用户定义的值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54799132/

相关文章:

ios - Swift 4 与 unity3d 5.6.6f2 的集成

r - 如何在MacOS上下载Sf包

macos - 在 Mac 上为 iPhone 交叉编译?

ios - 如何在 Swift 中使用 Yelp API?

objective-c - iPad 3 应用程序开发的图像大小(分辨率)是多少?

swift - iOS 8 SDK、Swift、MapKit 绘制路线

xcode - 如何使用 CMake 在 "Other linker flags"中设置库?

objective-c - 重新显示我的主 Cocoa 应用程序窗口

ios - Firebase 数据库分离监听器

ios - 如何使用 Vertical constraintsWithVisualFormat (SWIFT) 实现 UIScrollView