Search code examples
iosswiftuserdefaults

userdefaults not being saved after first time


I created some simple system that if userdefaults have key "isWalkthroughPresented". If the key is false then show walkthourghViewController. If it doesn't have the key then check from database.

However it doesn't set the key after first time. But saves after some launches. What should be the problem?

This is the code I use inside viewDidAppear after user has signed in and sees second ViewController:

let userDefaults = UserDefaults.standard

        if !userDefaults.bool(forKey: "isWalkthroughPresented") {

            presentWalkthrough()

            userDefaults.set(true, forKey: "isWalkthroughPresented")

        }else{
            checkIfCurrentUserHasOpenedTheAppBefore()//this just checks if user in db has the value
        }

Solution

  • After setting the user defaults value, call this to force saving the changes to database:

    //...
    userDefaults.set(true, forKey: "isWalkthroughPresented")
    userDefaults.synchronize()
    

    Normally the synchronize() method is called periodically to save the cached user settings to database. The interval between you set the "isWalkthroughPresented" and read it again is not enough to synchronize() get automatically called.

    See also these details from the method documentation:

    Because this method [synchronize()] 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.