I am using the following code to save an object to UserDefaults (previously NSUserDefaults) using xcode 8:
let defaults = UserDefaults.standard() defaults.set(someObject, forKey: "someObject") print(defaults.object(forKey: "someObject"))
someObject is a dictionary and I am running on the simulator.
For some reason this is not saving the value and 'nil' is printed. Wondering if it's a simulator problem.
We access the shared defaults object through the standard class property of the UserDefaults class. We then create a dictionary of type [String:String] and store the dictionary in the user's defaults database by invoking the set(_:forKey:) method of the UserDefaults database.
There's no straight way to save UIColor with UserDefaults so we will have to manipulate the type a bit. We are going to convert UIColor to Data and save it as any? . To convert the type of UIColor , we will need to use a special method called NSKeyedArchiver . Therefore, let's make an extension to the UserDefaults .
To store the string in the user's defaults database, which is nothing more than a property list or plist, we pass the string to the set(_:forKey:) method of the UserDefaults class. We also need to pass a key as the second argument to the set(_:forKey:) method because we are creating a key-value pair.
For Swift 3
UserDefaults.standard.setValue(token, forKey: "user_auth_token") print("\(UserDefaults.standard.value(forKey: "user_auth_token")!)")
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With