Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to for loop in userDefaults swift

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!)
like image 605
Punya Avatar asked Jul 06 '17 09:07

Punya


2 Answers

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")!)")
like image 159
Lal Krishna Avatar answered Oct 23 '22 03:10

Lal Krishna


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() {

}
like image 22
Kevin Machado Avatar answered Oct 23 '22 04:10

Kevin Machado