Search code examples
swifttimer

swift: how would I run a function at a scheduled time weekly


I want to be able to run a function that would clean out the UserDefaults in my app weekly at a specific time, does anyone happen to know how?


Solution

  • You can’t run code at a particular date/time. When you schedule background tasks (in iOS 13 and later), they’re performed at a time of the sole discretion of the OS (but you can tell it to not run it before a particular date/time). If you really want to run some background task, I’d suggest you watch the WWDC 2019 video Advances in App Background Execution.

    But I might suggest an easier pattern. Rather than clearing it out “weekly at a specific time”, think of it as an “expiration date”. Do you really need user defaults cleared exactly at 7am on Monday, or do you really only need to make sure that the data is removed if and when the user fires up the app after that date?

    So, you might have the app retrieve the “expiration date” from persistent storage and check to see the current date is greater than that date. If so, do whatever you want (e.g., clear out persistent storage or cached data or whatever).

    That begs the question of how you calculate the expiration date that you want to store in conjunction with other data in the data store. If you wanted it to be next Monday @ 7am, it would be:

    let components = DateComponents(hour: 7, weekday: 2)
    let expirationDate = Calendar.current.nextDate(after: Date(), matching: components, matchingPolicy: .nextTime)!
    

    Or, if you wanted it to just set it to be seven days from now:

    let expirationDate = Calendar.current.date(byAdding: .day, value: 7, to: Date())