我正在尝试在.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)
我的列表如下:
我已经在“项目”>“目标”中添加了用户定义的构建设置
为什么找不到在其中添加的值?我究竟做错了什么?
答案 0 :(得分: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
}
除此之外,您需要检查以下内容
转到打包并检查Info Plist
文件。它必须是您的主要Info Plist文件。
检查Info Plist您如何在Info Plist文件中获取用户定义的值
答案 1 :(得分: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