Settings bundle values returning nil

后端 未结 4 1613
青春惊慌失措
青春惊慌失措 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:15

    You should register your defaults so that it will sync up. source from here

    // Swift 3
    var appDefaults = Dictionary()
    appDefaults["mySettingKey"] = "http://www.example.com" // Default Value
    
    UserDefaults.standard.register(appDefaults)
    UserDefaults.standard.synchronize()
    
    let mySettingValue = UserDefaults.standard.string(forKey: "mySettingKey")
    

    Keep in mind that you should also use registerDefaults: when your app uses a Settings Bundle. Since you already specified default values inside the settings bundle’s plist, you may expect that your app picks these up automatically. However, that is not the case. The information contained in the settings bundle is only read by the iOS Settings.app and never by your app. In order to have your app use the same defaults as shown inside the Settings.app, you have to manually copy the user defaults keys and their default values into a separate plist file and register it with the defaults database as shown above.

提交回复
热议问题