-1

I want to remove all object in userdefaults. while hitting the logout button. expect one bool key should not remove.May i know its possible

func resetUserDefaults() {

    print("userDefaults successfully removed from the app")

    let userDefaults = UserDefaults.standard
    let dict = userDefaults.dictionaryRepresentation()

    dict.keys.forEach { key in        
       userDefaults.removeObject(forKey: key)
     }
}
Andrew
  • 26,706
  • 9
  • 85
  • 101
chaitanya
  • 9
  • 6

4 Answers4

1

Let's add condition like this

 dict.keys.forEach { key in 
        if key != "YouBoolKey" {
            userDefaults.removeObject(forKey: key)
        }
 }

And dont forget to synchronize at the end

UserDefaults.standard.synchronize()
jacob
  • 1,024
  • 9
  • 14
  • 1
    You don't need to call [synchronize](https://developer.apple.com/documentation/foundation/userdefaults/1414005-synchronize) any more – Andrew Oct 11 '19 at 11:34
1

I'd prefer:

for key in dict.keys where key != "YouBoolKey" {
    userDefaults.removeObject(forKey: key)
}
basvk
  • 4,437
  • 3
  • 29
  • 49
0

A simple approach is, just put the login data in one Object (Structure), save that to UserDefaults and remove that while pressing the logout button.

You may refer the link.

0

see my way at: How to remove all data by a suite name from UserDefaults in Swift?

in wipe data. You can also use a for... on your array of KEYS.

ingconti
  • 10,876
  • 3
  • 61
  • 48