How to remove all UserDefaults data ? – Swift [duplicate]

The problem is you are printing the UserDefaults contents, right after clearing them, but you are not manually synchronizing them.

let domain = Bundle.main.bundleIdentifier!
UserDefaults.standard.removePersistentDomain(forName: domain)
UserDefaults.standard.synchronize()
print(Array(UserDefaults.standard.dictionaryRepresentation().keys).count)

This should do the trick.

Now you don’t normally need to call synchronize manually, as the system does periodically synch the userDefaults automatically, but if you need to push the changes immediately, then you need to force update via the synchronize call.

The documentation states this

Because this method is automatically invoked at periodic intervals, use this method only if you cannot wait for the automatic synchronization (for example, if your application is about to exit) or if you want to update the user defaults to what is on disk even though you have not made any changes.

Leave a Comment

tech