Reputation: 2408
I'm trying to retrieve user-defined build settings in my .plist. I'm working on a Mac app and I'm using the Info.plist (shouldn't be a custom one, right?)
I use the following code to retrieve my values from the 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
}
}
This will print:
$(YT_SERVER_URL)
$(YT_APP_NAME)
My plist looks like this:
I've added my user-defined build settings in my Project > Targets
Why can't I find the values I've added there? What am I doing wrong?
Upvotes: 1
Views: 2618
Reputation: 1104
Using these lines you can get the Plist dictionary ::
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
Upvotes: 0
Reputation: 2859
First of all, you can access user-defined values from your Plist
. To access the user-defined value from Plist
you need to add the following code :
extension Bundle {
var apiBaseURL: String {
return object(forInfoDictionaryKey: "serviceURL") as? String ?? ""
}
}
Usage :
let appConfiguration = Bundle.main.apiBaseURL
Your applicationDidFinishLaunching
will look like this:
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
}
Apart from that, you will need to check the following things
Go to Packaging and check Info Plist
File. it must be your main Info Plist file.
Check Info Plist How you have fetched user-defined value in Info Plist file
Upvotes: 2