Save dictionary in userdefaults in swift 3 with xcode 8

NsuserdefaultsSwift3Xcode8Ios10

Nsuserdefaults Problem Overview


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.

Nsuserdefaults Solutions


Solution 1 - Nsuserdefaults

For Swift 3

UserDefaults.standard.setValue(token, forKey: "user_auth_token")
print("\(UserDefaults.standard.value(forKey: "user_auth_token")!)")

Solution 2 - Nsuserdefaults

Working perfectly here with this..!

    let dict:[String:String] = ["key":"Hello"]
    UserDefaults.standard.set(dict, forKey: "dict")
    let result = UserDefaults.standard.value(forKey: "dict")
    print(result!)
    // Output -> { key:hello;}

Solution 3 - Nsuserdefaults

This is the undocumented-but-known issue that NSUserDefaults/UserDefualts does not work in the iOS 10 simulator if the iOS 8/9 simulator has been previously run.

Rebooting your Mac and going straight to XCode 8, iOS 10 simulator will fix this issue.

See also: https://stackoverflow.com/questions/37824190/why-wont-my-app-run-in-xcode-8-beta-8s128d/37824276#37824276

Solution 4 - Nsuserdefaults

This problem seems to be caused by having two versions of xcode/simulator installed.

What worked for me was uninstalling xcode 7 and just keeping xcode 8 beta on my system. Emptying trash, resetting the simulator and running. I also restarted my computer.

After following these steps the simulator is able to save to UserDefaults.

Solution 5 - Nsuserdefaults

Swift 4:-

let defaults = UserDefaults.standard

let dictionary: [String:String] = ["key":"Value"]  //Dictionary which you want to save

defaults.setValue(dictionary, forKey: "DictValue") //Saved the Dictionary in user default

let dictValue = defaults.value(forKey: "DictValue") //Retrieving the value from user default 

print(dictValue)  // Printing the value 

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionalionthegoView Question on Stackoverflow
Solution 1 - NsuserdefaultsJanView Answer on Stackoverflow
Solution 2 - NsuserdefaultsBishow GurungView Answer on Stackoverflow
Solution 3 - NsuserdefaultsRichardView Answer on Stackoverflow
Solution 4 - NsuserdefaultsalionthegoView Answer on Stackoverflow
Solution 5 - NsuserdefaultsSandeep VishwakarmaView Answer on Stackoverflow