Last active
May 2, 2024 22:47
-
-
Save dougdiego/945fd2e33769cf5f1338 to your computer and use it in GitHub Desktop.
Migrate NSUserDefaults to App Groups - Swift
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
func migrateUserDefaultsToAppGroups() { | |
// User Defaults - Old | |
let userDefaults = NSUserDefaults.standardUserDefaults() | |
// App Groups Default - New | |
let groupDefaults = NSUserDefaults(suiteName: "group.myGroup") | |
// Key to track if we migrated | |
let didMigrateToAppGroups = "DidMigrateToAppGroups" | |
if let groupDefaults = groupDefaults { | |
if !groupDefaults.boolForKey(didMigrateToAppGroups) { | |
for key in userDefaults.dictionaryRepresentation().keys { | |
groupDefaults.setObject(userDefaults.dictionaryRepresentation()[key], forKey: key) | |
} | |
groupDefaults.setBool(true, forKey: didMigrateToAppGroups) | |
groupDefaults.synchronize() | |
print("Successfully migrated defaults") | |
} else { | |
print("No need to migrate defaults") | |
} | |
} else { | |
print("Unable to create NSUserDefaults with given app group") | |
} | |
} |
This is super helpful, thank you!
I don't really understand why would you call userDefaults.dictionaryRepresentation()
twice when you can just do
for (key, value) in standardDefaults.dictionaryRepresentation() {
groupDefaults.set(value, forKey: key)
}
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
thx so much!