Settings bundle values returning nil

后端 未结 4 1612
青春惊慌失措
青春惊慌失措 2021-01-04 22:25

I added a Settings bundle to my app and in Xcode it appears in the root of my project tree view.

The Root.plist file looks like this:

&l         


        
4条回答
  •  无人及你
    2021-01-04 23:06

    You need to manually read the default values from Settings.bundle and add them to the UserDefaults registration domain, which can be done with UserDefaults.register(). By using the registration domain, the values are held in memory (volatile), so calling UserDefaults.synchronize() is not needed.

    Swift 4 and 5

    Here's a few lines of Swift that will get the job done:

    // Register the default values from Settings.bundle
    if let settingsURL = Bundle.main.url(forResource: "Root", withExtension: "plist", subdirectory: "Settings.bundle"),
        let settingsRootDict = NSDictionary(contentsOf: settingsURL),
        let prefSpecifiers = settingsRootDict["PreferenceSpecifiers"] as? [NSDictionary],
        let keysAndValues = prefSpecifiers.map({ d in (d["Key"], d["DefaultValue"]) }) as? [(String, Any)] {
            UserDefaults.standard.register(defaults: Dictionary(uniqueKeysWithValues: keysAndValues))
    }
    

提交回复
热议问题