简体   繁体   English

在 SwiftUI 运行后台任务

[英]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.我正在制作一个应用程序,其中包含用户位置,并且每 10 秒就会有一个用户周围的圆圈缩小,我已经让这部分工作正常(使用时间间隔为 10 秒的计时器,然后在 text() 上使用 a.onRecieve .) 当用户点击主页按钮或关闭他们的手机时,我如何让这个计时器在后台运行,以及我如何让圆圈在手机关闭时不断缩小,或者在应用程序再次打开。

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).决定您希望如何保存数据(UserDefaults 和 CoreData 是两个常见选项)。 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.当应用程序下次启动时(决定您要使用哪种方法——在您的@main 中进行初始化,在您的 ContentView 中进行 onAppear,等等),从持久存储中获取日期,并将其与当前日期进行比较。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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