According to the example here
you simply pass in the Realm.Configuration to the View like so
AnyView ().environment(\.realmConfiguration, Realm.Configuration(...))
And within the View create a variable to access the realm objects
@ObservedResults(Object.Self) var objects
should use the realm configuration being passed in but this does not seem to work.
I have the following:
extension Realm {
static var IAMRealm: Realm? {
let configuration = Realm.defaultConfig
do {
let realm = try Realm(configuration: configuration)
return realm
} catch {
os_log(.error, "Error opening realm: \(error.localizedDescription)")
return nil
}
}
**static** **var** defaultConfig: Realm.Configuration {
**return** Realm.Configuration(schemaVersion: 1)
}
**static** **func** setDefaultConfig(){
Realm.Configuration.defaultConfiguration = Realm.defaultConfig
}
}
**private** **struct** RealmConfigurationKey: EnvironmentKey {
**static** **let** defaultValue = Realm.defaultConfig
}
**extension** EnvironmentValues {
**var** realmConfiguration: Realm.Configuration {
**get** { **self** [RealmConfigurationKey. **self** ] }
**set** { **self** [RealmConfigurationKey. **self** ] = newValue }
}
}
The only way I could get it to work was by calling the following from the SwiftUI.App prior to returning the main window.
@main
struct RealmApp: SwiftUI.App {
@NSApplicationDelegateAdaptor(AppDelegate.self) var appDelegate
var body: some Scene {
initialise()
return WindowGroup {
ContentView()
}
.windowStyle(HiddenTitleBarWindowStyle())
.windowToolbarStyle(UnifiedCompactWindowToolbarStyle(showsTitle: true))
}
func initialise() {
Realm.Configuration.defaultConfiguration = Realm.defaultConfig
}
}
Am I doing something wrong when using the .environment(.realmConfiguration, …) option ?
Apologies for all the **s - how can I stop that happening when pasting in from Xcode ?