Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
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")
}
}
@PedroCavaleiro

This comment has been minimized.

Copy link

PedroCavaleiro commented Aug 10, 2018

An updated version of your code to Swift 4

func migrateUserDefaultsToAppGroups() {
        
        // User Defaults - Old
        let userDefaults = UserDefaults.standard
        
        // App Groups Default - New
        let groupDefaults = UserDefaults(suiteName: "group.myGroup")
        
        // Key to track if we migrated
        let didMigrateToAppGroups = "DidMigrateToAppGroups"
        
        if let groupDefaults = groupDefaults {
            if !groupDefaults.bool(forKey: didMigrateToAppGroups) {
                for key in userDefaults.dictionaryRepresentation().keys {
                    groupDefaults.set(userDefaults.dictionaryRepresentation()[key], forKey: key)
                }
                groupDefaults.set(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")
        }
        
    }
@zborovskyi

This comment has been minimized.

Copy link

zborovskyi commented Feb 24, 2020

thx so much!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.