How can DeviceActivityMonitor extension communicate with my main app?

At 11:37 in this video - https://developer.apple.com/videos/play/wwdc2021/10123/ - Nolan instantiates MyModel() in swiftui view file. And then at 12:02 he just uses MyModel from extension.

I have the exact same code and when I try to build my project, it fails with error that MyModel() could not be found.

I shared my MyModel.swift file between extension target and main app. Now it builds. However, it seems there are two separate instances of MyModel.

  1. What is proper way for DeviceActivityMonitor extension to pass data to main app? I simply want to increment counter from extension every minute and let the main app to know that.
  2. Or even better, - is there a way to use SwiftData from Device Activity Monitor extension?

Replies

The extension and the application are different processes so: They are 2 different instances because each one "lives" on a different process . You can use a shared userDefaults or any other persistency (you can share a database file and change it in one process and read from the other) Read this: [https://developer.apple.com/library/archive/documentation/General/Conceptual/ExtensibilityPG/ExtensionScenarios.html) Good luck