Swift - How to set initial value for NSUserDefault

2019-02-04 05:07发布

I have a switch called soundSwitch, I am saving the state of the button using an user default as such:

@IBAction func soundsChanged(sender: AnyObject) {
        if soundSwitch.on{
            defaults.setBool(true, forKey: "SoundActive")
            print("Sound ON")
        }else{
            defaults.setBool(false, forKey: "SoundActive")
            print("Sound OFF")
        }
    }

Currently the actual defaults value is initially false when the user first launches the application.

How do I implement the defaults to be true if the user is first launching the app and it they haven't been configured yet.

I have seen methods in Objective-C, but nothing in Swift. From what I have seen you can do it in the app delegate some how, or in a plist file. How do I do either of those ones?

9条回答
干净又极端
2楼-- · 2019-02-04 05:27

Using "registerDefaults" you can set Default value of NSUserDefaults

let userDefaultsDefaults = [
            "SoundActive" : true
        ]

NSUserDefaults.standardUserDefaults().registerDefaults(userDefaultsDefaults)

Note: write this in didFinishLaunchingWithOptions, so default value is set.

write below code where you want to check

 let onoroff = NSUserDefaults.standardUserDefaults().objectForKey("SoundActive") as! Bool!

 if (onoroff != nil && onoroff == false)
 {
    self.checkForAgreement()
 }
查看更多
贪生不怕死
3楼-- · 2019-02-04 05:29

Put this in your "didFinishLaunchingWithOptions" in your AppDelegate.

if defaults.valueForKey("launchedAlready") == true {
       print("Not first launch.")
    }
    else {
       defaults.setValue(true, forKey: "launchedAlready")
        defaults.setBool(true, forKey: "SoundActive")
        print("Sound ON")
    }
查看更多
Deceive 欺骗
4楼-- · 2019-02-04 05:46

Add this to your didFinishLaunchingWithOptions method from the AppDelegate. As some others pointed out try not to abuse by putting everything in this method.

 func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {

    /// Here you can give default values to your UserDefault keys
    UserDefaults.standard.register(defaults: [
        "SoundActive": true,
        "someOtherKey": "Some Message"
        ])
}
查看更多
smile是对你的礼貌
5楼-- · 2019-02-04 05:47

Swift 4

I prefer to implement a function similar to UserDefaults.string(forKey: ) which returns nil if the value is not set. Combined with the ?? operator, you don't need to have any default values written to disk unless you explicitly set them later.

extension UserDefaults {

    public func optionalInt(forKey defaultName: String) -> Int? {
        let defaults = self
        if let value = defaults.value(forKey: defaultName) {
            return value as? Int
        }
        return nil
    }

    public func optionalBool(forKey defaultName: String) -> Bool? {
        let defaults = self
        if let value = defaults.value(forKey: defaultName) {
            return value as? Bool
        }
        return nil
    }
}

Then you can retrieve your default values as follows

let defaults = UserDefaults.standard
let userName = defaults.string(forKey: "Username") ?? "Happy"
let userAge = defaults.optionalInt(forKey: "Age") ?? 21
let isSmart = defaults.optionalInt(forKey: "Smart") ?? true
查看更多
贼婆χ
6楼-- · 2019-02-04 05:49

Set and get sound activated.

  var isSoundActivated: Bool {
        get {
            return defaults.bool(forKey: "SoundActive")
        }
        set {
            defaults.set(newValue, forKey: "SoundActive")
            defaults.synchronize()
        }
    }

Set bool value by

isSoundActivated = true

check bool value by

if isSoundActivated {
  print("sound activated")
}
查看更多
Deceive 欺骗
7楼-- · 2019-02-04 05:52

Swift 3 syntax example

Register a boolean default value:

UserDefaults.standard.register(defaults: ["SoundActive" : true])

And to get the value:

UserDefaults.standard.bool(forKey: "SoundActive")

Sidenote: Although the above code will return true, note that the value isn't actually written to disk until you set it:

UserDefaults.standard.set(true, forKey: "SoundActive")
查看更多
登录 后发表回答