2

I have an app that uses Core Data with CloudKit. Changes are synced between devices.

Main target has Background Modes capability with checked "Remote notifications". Main target and widget target both have the same App Group, and both have iCloud capability with Services set to CloudKit and same container in Containers checked.

For accessing Core Data data from widget I use CoreDataStack, as shown in this answer. In WidgetKit file I have a function that performs fetch request and returns Int — a number of rows from that request. Later I show that number in widget view.

But, if Core Data data in CloudKit changes, for example — on another device user added or deleted records, that Int may be incorrect.

How to request update WidgetKit timeline entries, when such changes happens? (If data changed on another device or on a current device.) Thanks.

Igor R.
  • 399
  • 4
  • 23

2 Answers2

0

A possible solution is to observe the NSPersistentStoreRemoteChange notification.

In your Core Data Stack:

let container = NSPersistentContainer(name: "MyStuff")
let description = container.persistentStoreDescriptions.first
description?.setOption(true as NSNumber, forKey: NSPersistentStoreRemoteChangeNotificationPostOptionKey)

And then you can detect the notifications like described here:


There is one drawback though: when the remote changes are detected this notification is fired more than once (usually in short series). To avoid refreshing too often, you may want to use a Timer to delay refreshing.

pawello2222
  • 46,897
  • 22
  • 145
  • 209
  • Can same be done without remote change notification? For example, when data changed on a device that shows widget? Or in that case remote change notification still be fired? – Igor R. Sep 19 '20 at 11:58
  • If your data is changed on the device (locally), it will be pushed to the cloud and then the remote notification will be fired as well. For your local Persistent Container changes you can use the `NSManagedObjectContextObjectsDidChangeNotification`. The only problem with all these notifications is that they may fire more often than you'd like, so use them wisely. – pawello2222 Sep 19 '20 at 12:31
0

How to request update WidgetKit timeline entries, when such changes happens? (If data changed on another device or on a current device.)

You have to reload the Widget's timeline. You can do it from you main app target, by importing WidgetKit. You can do that when you save the context or when you process remote changes.

You can either update all widgets

WidgetCenter.shared.reloadAllTimelines()

Or only the widget you need

WidgetCenter.shared.reloadTimelines(ofKind: "kind")

More info on Apple docs

imthath
  • 1,353
  • 1
  • 13
  • 35