我有一个 UserDefaults
bool 值,它告诉我何时必须在第一次安装该应用程序时展示我的演练。当我安装它时,键“firstAccessToApp”的 bool 值从 true 变为为 false,但如果我从我的设备中删除应用程序并重新安装它,我的演练不会出现,因为 bool 值仍然是 false。当我从设备中删除我的应用程序时如何更改值?这是我的代码:
if !defaults.bool(forKey: "firstAccessToApp") {
present(Walkthrough(), animated: true, completion: nil)
UserDefaults.standard.set(true, forKey: "firstAccessToApp")
UserDefaults.standard.synchronize()
}
最佳答案
当您安装应用程序时,UserDefaults 中不存在该 key ,如果您尝试访问它,它将返回默认值,即 false
。要在首次安装和打开应用程序时将其设置为 true
,您可以将此代码添加到 func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool
方法:
let defaults = UserDefaults.standard
if (!defaults.dictionaryRepresentation().keys.contains("firstAccessToApp")) {
defaults.set(true, forKey: "firstAccessToApp")
defaults.synchronize()
}
关于swift - 删除应用程序时更改 UserDefaults bool 值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40869811/