Is there a way to have the same function repeat every day?

For example, repeat func getNewSentence() in the app every 24 hours so that it generates a new sentence/refreshes itself every day at midnight?

This is regardless of whether the user opens the app or not, so when they do open it the new sentence would appear. The sentence should be in the app for a 24 hours before renewing.

I was thinking of using Timer() and adding it to backgroundAppRefresh but after some research it seems discouraged/bad practice.

I believe you want to cache (store) the most recent value and the date it was created. Then when the value is accessed, first check its age and if it is too old then get a new one.

1 Like

If you wanted to display a UserNotification to display the new sentence, check out this article:
100DaysOfSwiftUI - Scheduling Local Notifications

There may be other articles in this series that might also come in handy there. It has been a tremendous resource for me.

Good luck with it.

1 Like

This is regardless of whether the user opens the app or not

Based on this I’m assuming you’re working on iOS. If so, I’m going to recommend that you pop on over to Apple Developer Forums. Background execution on iOS is an issue with many facets, and none of them are Swift specific (you’d have the same issues if you were working in Objective-c).

Tag your question with BackgroundTasks so that I see it.

Share and Enjoy

Quinn “The Eskimo!” @ DTS @ Apple


Thank you!

Thanks! =)