2

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
        }
4

1 回答 1

3

设置用户默认值后,调用它来强制保存对数据库的更改:

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

通常,该synchronize()方法会定期调用以将缓存的用户设置保存到数据库。您设置和再次读取之间的间隔"isWalkthroughPresented"不足以synchronize()自动调用。

另请参阅方法文档中的这些详细信息:

由于此方法 [synchronize()] 会定期自动调用,因此仅当您无法等待自动同步(例如,如果您的应用程序即将退出)或您想要更新用户默认值时才使用此方法即使您没有进行任何更改,它也在磁盘上。

于 2016-10-27T10:29:54.587 回答