8

I am saving data into userDeafults using 2 textfield as String, String but I want to know how to retrieve all the data to display either using loop or function

    let save = UserDefaults.standard

    let heading = headingText.text
    let description = desxriptionTexr.text
    save.set(description, forKey: heading!)
Punya
  • 353
  • 1
  • 3
  • 12

4 Answers4

19

To get all keys and corresponding values in UserDefaults, you can use:

for (key, value) in UserDefaults.standard.dictionaryRepresentation() {
            print("\(key) = \(value) \n")
}

In swift 3, you can store and retrieve using:

UserDefaults.standard.setValue(token, forKey: "user_auth_token")
print("\(UserDefaults.standard.value(forKey: "user_auth_token")!)")
Lal Krishna
  • 15,485
  • 6
  • 64
  • 84
1

I think is not a correct way to do.

I suggest you to put your values into a dictionary and set the dictionary into the UserDefaults.

let DictKey = "MyKeyForDictionary"
var userDefaults = UserDefaults.standard

// create your dictionary
let dict: [String : Any] = [
    "value1": "Test",
    "value2": 2
]

// set the dictionary
userDefaults.set(dict, forKey: DictKey)

// get the dictionary
let dictionary = userDefaults.object(forKey: DictKey) as? [String: Any]

// get value from
let value = dictionary?["value2"]


// iterate on all keys
guard let dictionary = dictionary else {
    return
}
for (key, val) in dictionary.enumerated() {

}
Kevin Machado
  • 4,141
  • 3
  • 29
  • 54
0

Here you are setting the key as heading and the value as description. You can retrieve the value from userDefaults using UserDefaults.standard.object(forKey:), UserDefaults.standard.string(forKey: ),UserDefaults.standard.value(forKey: ) etc functions.

So its better to save heading and description for 2 different keys may be like

let save = UserDefaults.standard
let heading = headingText.text
let description = desxriptionTexr.text
save.set(description, forKey: "description")
save.set(heading, forKey: "heading")

And you could retrieve like

 let description = UserDefaults.standard.string(forKey:"description")
 let heading = UserDefaults.standard.string(forKey:"heading")
Aravind A R
  • 2,674
  • 1
  • 15
  • 25
0

If you have multiple Strings, simply save value as array

UserDefaults.standard.set(YourStringArray, forKey: "stringArr")

let arr = UserDefaults.standard.stringArray(forKey: "stringArr")

for s in arr! {
    //do stuff
}
Fangming
  • 24,551
  • 6
  • 100
  • 90