简体   繁体   中英

Run a background task in SwiftUI

im making an app where it has the users location and every 10 seconds theres a circle around the user that shrinks, ive got that part all working (using a timer with a time interval of 10 secs, then a.onRecieve on a text().) how do i make this timer run in the background when the user clicks the home button or turns off their phone, and how do i also make the circle keep shrinking while the phone is off, or update it to the right size when the app is opened again.

you don't continue running a timer. You store the time that the event started and next time the app is opened, you see how much time has elapsed since that stored value

Decide how you want to persist your data (UserDefaults and CoreData are two common options). Store the date. When the app next starts up (decide which method you want to use -- init in your @main, onAppear in your ContentView, etc), get the date out of the persisted store, and compare it to the current date.

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