在应用程序在后台或前景时节省给Coredata
当我的应用在监视新锻炼时,当我的应用在后台处于后台时,我有一个hkobserverquery成功触发。但是,随后触发的函数更新并保存了正在创建问题的Coredata视图上下文。
所有功能,包括使用单个NSManagedObjectContext传递给视图模型的单个NSManagedObjectContext,包括从可观察的对象视图模型运行的HKOBServerQuery和Coredata Crud函数。
视图上下文在后台运行时保存,但是在前景中运行时,我会发现此错误:
不允许从背景线程发布更改;确保从主线程发布值(通过模型更新上的接收器(:)诸如接收器(例如)。
。
保存下来时:
if self.viewContext.hasChanges {
do {
try self.viewContext.save()
} catch {
print(error)
}
}
如果我使用dispatchqueue.main.async将视图上下文的保存保存到主线程,则保存在应用程序在后台(应用程序进入前景一旦优先考虑),但是沉默这个警告。
在背景中与前景功能时,使用@mainactor会产生相同的问题。
我对线程/队列的理解是有限的。缺少创建2个单独的功能,一个用于背景,一个用于前景,是否有一种动态使用正确的线程/队列的方法?
I've got a HKObserverQuery that triggers successfully when my app is in the background while monitoring for new workouts. However it is the subsequently triggered function that updates and saves the CoreData view context that is creating issues.
All functions, including the HKObserverQuery and CoreData CRUD function run from an observable object view model, using a single NSManagedObjectContext passed in to the view model.
The view context saves while running in the background, but when running in the foreground I get this error:
Publishing changes from background threads is not allowed; make sure to publish values from the main thread (via operators like receive(on:)) on model updates.
When saving as such:
if self.viewContext.hasChanges {
do {
try self.viewContext.save()
} catch {
print(error)
}
}
If I move the saving of the view context to the main thread using DispatchQueue.main.async, then the save won't function while the app is in the background (recommencing once the app enters the foreground), but silences this warning.
Using @MainActor creates the same issues when functioning in the background vs the foreground.
My understanding of threads/queues is limited. Short of creating 2 separate functions, one for background and one for foreground, is there a way to dynamically use the correct thread/queue?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您可以为此使用
ScenePhase
。我会将其添加到应用结构或初始化视图模型的任何地方。
文档
You could use
ScenePhase
for this.I would add this to the App struct or where ever you initialize your viewmodel.
Documentation