I have initialized realm in the init of the @main app point like this:
init() {
let fileURL = FileManager.default.containerURL(forSecurityApplicationGroupIdentifier: "group.com.identifier")!
.appendingPathComponent("default.realm")
let config = Realm.Configuration(fileURL: fileURL)
// Set this configuration as the default for Realm across the app
Realm.Configuration.defaultConfiguration = config
}
And i have a realm data manager like this:
class SetupDataManager {
static let shared = SetupDataManager()
private var realm: Realm {
get {
return try! Realm()
}
}
private init() {}
func fetchBalancedActivityModel(by id: String) async -> BalancedActivityModel? {
return realm.object(ofType: BalancedActivityModel.self, forPrimaryKey: id)
}
}
And these work well enough for when the app is active and i want to save and fetch the balancedActivityModels and even use @ObservedResults(BalancedActivityModel.self) var balancedActionItems in my views.
However i'm also using the DeviceActivity api and i want to fetch these balancedActivityModels in my DeviceActivityMonitorExtension and specifically when the function eventDidReachThreshold gets called.
Now i'm confused about how to initialize another realm and thread to go with it and access the saved models in the background.. currently i have the function implemented like this but this really doesn't work
override func eventDidReachThreshold(_ event: DeviceActivityEvent.Name, activity: DeviceActivityName) {
super.eventDidReachThreshold(event, activity: activity)
let fileURL = FileManager.default
.containerURL(forSecurityApplicationGroupIdentifier: "group.com.identifier")!
.appendingPathComponent("default.realm")
let config = Realm.Configuration(fileURL: fileURL)
Realm.Configuration.defaultConfiguration = config
let realm = try! Realm()
guard let balancedActivityModel = realm.object(ofType: BalancedActivityModel.self, forPrimaryKey: activity.rawValue) else {
return
}
.. rest of the code like
realm.writeAsync {
balancedActivityModel.timeIsUp = true
balancedActivityModel.count += 1
}
doesn't work..
}
Any tips appreciated!
Initialize new realm from extension..