简体   繁体   中英

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. 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. I have tried on an iPhone and on the simulator (Device->Erase all Content and Settings).

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?

Is there a way of running a code only during the app's installation where I can reset those userDefaults keys?

NSUserDefaults might not be deleted after you delete the app. The solution would be:

  • You could make a button or something, that would clean local storage
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")
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM