[英]UserDefaults are not removed after app is uninstalled
I am running the following code我正在运行以下代码
static func setupNewUserNotifications() {
let defaults = UserDefaults.standard
let userHasBeenNotified = defaults.bool(forKey: "userHasBeenNotified")
guard userHasBeenNotified == false else {
return
}
// SCHEDULE NOTIFICATION 1 HOUR AFTER FIRST USE
let content = UNMutableNotificationContent()
content.title = "Title"
content.body = "Content."
content.sound = UNNotificationSound.default
let trigger = UNTimeIntervalNotificationTrigger(timeInterval: 3600, repeats: false)
let request = UNNotificationRequest(identifier: "NewUser", content: content, trigger: trigger)
UNUserNotificationCenter.current().add(request)
defaults.set(true, forKey: "userHasBeenNotified")
}
I call this function from the AppDelegate when the app is sent to the background.当应用程序发送到后台时,我从 AppDelegate 调用此函数。 The idea is for the notification to be set once.这个想法是让通知设置一次。 The code works fine.该代码工作正常。 However, when I uninstall the app and reinstall to test again, the value for userHasBeenNotified continues being true.但是,当我卸载应用程序并重新安装以再次测试时,userHasBeenNotified 的值仍然为真。 I have tried on an iPhone and on the simulator (Device->Erase all Content and Settings).我已经在 iPhone 和模拟器上尝试过(设备->擦除所有内容和设置)。
Only if I change the identifier and run do I get the app to behave as intended.只有当我更改标识符并运行时,我才能让应用程序按预期运行。 But then if I uninstall and try again, the same thing happens.但是,如果我卸载并重试,也会发生同样的事情。
Why are UserDefaults not getting removed after uninstalling?为什么卸载后没有删除 UserDefaults?
Is there a way of running a code only during the app's installation where I can reset those userDefaults keys?有没有办法仅在应用程序安装期间运行代码,我可以在其中重置那些 userDefaults 键?
NSUserDefaults might not be deleted after you delete the app.删除应用程序后,NSUserDefaults 可能不会被删除。 The solution would be:解决方案是:
let defaults = UserDefaults.standard
defaults.set(true, forKey: "userHasBeenNotified")
let userHasBeenNotified = defaults.bool(forKey: "userHasBeenNotified")
if userHasBeenNotified == true
{
print("USER HAS BEEN NOTIFIED")
defaults.set(nil, forKey: "userHasBeenNotified")
}
// NOW TRY // 现在试试
if userHasBeenNotified == true
{
print("USER HAS BEEN NOTIFIED")
}
else
{
print("USER DEFAULTS FOR 'userHasBeenNotified' HAS NO VALUE")
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.