I tried this code but it brings me all keys saved except me. How can I get my own saved keys?
print("UD: \(UserDefaults.standard.dictionaryRepresentation().keys) \n")
Console:
The key I saved is "Ağustos Test 1". How can I get only this key?
I tried this code but it brings me all keys saved except me. How can I get my own saved keys?
print("UD: \(UserDefaults.standard.dictionaryRepresentation().keys) \n")
Console:
The key I saved is "Ağustos Test 1". How can I get only this key?
IDEALLY you would know the key or group all your keys as a child of another key but thats not what you asked for :)
A few workarounds:
you COULD enumerate all keys in userDefaults BUT you have to be aware you'll get keys, that aren't yours...
let dict = UserDefaults.standard.dictionaryRepresentation()
for key in dict.keys {
if let value = dict[key] {
print("\(key) = \(value)")
}
}
This will print all that is in there and that includes almost a hundred apple config values. so.. no good!
if your keys have a commonality, you could invert the filter:
import Foundation
let included_prefixes = ["myprefs.", "myprefs2."]
//my keys
UserDefaults.standard.set(1, forKey: "myprefs.int1")
UserDefaults.standard.set("str1", forKey: "myprefs2.str1")
let dict = UserDefaults.standard.dictionaryRepresentation()
let keys = dict.keys.filter { key in
for prefix in included_prefixes {
if key.hasPrefix(prefix) {
return true
}
}
return false
}
for key in keys {
if let value = dict[key] {
print("\(key) = \(value)")
}
}
So if you really dont know your keys you COULD filter them out
import Foundation
let blacklisted_prefixes = ["Country", "NS", "com.apple", "com.omnigroup", "NavPanel", "WebAutomatic", "NSTableViewDefaultSizeMode", "sks_agent", "Apple", "PayloadUUID", "PKSecure", "_HI", "AK", "ContextMenu", "MultipleSession", "CSUI"]
//my keys
UserDefaults.standard.set(1, forKey: "int1")
UserDefaults.standard.set("str1", forKey: "str1")
let dict = UserDefaults.standard.dictionaryRepresentation()
let keys = dict.keys.filter { key in
for prefix in blacklisted_prefixes {
if key.hasPrefix(prefix) {
return false
}
}
return true
}
for key in keys {
if let value = dict[key] {
print("\(key) = \(value)")
}
}
BUT this is very fragile and not really advisable!
#needsmust
You cannot "get" from user defaults just the keys for user defaults entries that you created in code. What's in your user defaults is what's in your user defaults; it doesn't have any way of distinguishing "who" created a particular entry.
Knowing the keys you added is your business. Typically this information is hard-coded into your app, e.g. you have a list of constants, usually as static properties of an enum or struct. If you are creating keys dynamically, then if you need to know the names of the keys you created, storing that information is entirely up to you.