我正在尝试在我的 .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 是这样的:
我已经在我的项目 > 目标中添加了我的用户定义的build设置
为什么我找不到我在那里添加的值?我究竟做错了什么?
最佳答案
首先,您可以从您的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
}
除此之外,您还需要检查以下事项
转到打包并检查
Info Plist
文件。它必须是您的主要 Info Plist 文件。检查 Info Plist 您如何在 Info Plist 文件中获取用户定义的值
关于swift - 在 Plist 中检索用户定义的值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54799132/