Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Save dictionary in userdefaults in swift 3 with xcode 8

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.

like image 758
alionthego Avatar asked Jun 15 '16 03:06

alionthego


People also ask

How do I save a dictionary in Swift?

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.

How do you save UIColor in UserDefaults?

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 .

How do you save a String in 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.


Video Answer


1 Answers

For Swift 3

UserDefaults.standard.setValue(token, forKey: "user_auth_token") print("\(UserDefaults.standard.value(forKey: "user_auth_token")!)") 
like image 143
Jan Avatar answered Sep 28 '22 02:09

Jan