Skip to content

Instantly share code, notes, and snippets.

@dimohamdy
Forked from dougdiego/MigrateDefaults.swift
Created August 7, 2020 00:35
Show Gist options
  • Save dimohamdy/b89a60642c58d05cbf23a2ce966b9f21 to your computer and use it in GitHub Desktop.
Save dimohamdy/b89a60642c58d05cbf23a2ce966b9f21 to your computer and use it in GitHub Desktop.
Migrate NSUserDefaults to App Groups - Swift
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")
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment