Reputation: 682
I am struggeling with using a new defaultConfiguration for Realm (I think so...)
So what do I try to achieve. I'd like to change the default Realm URL to an Apple App group based ID because I want to use the same Realm from both the Today Extension of my App as well as my App itself.
I found a (slightly outdated Realm tutorial for WatchKit Extension ) where thy put the following to the AppDelegate
:
realmUrl: NSURL = NSFileManager.defaultManager().containerURLForSecurityApplicationGroupIdentifier("group.net.exchange.On")!
realmUrl.URLByAppendingPathComponent("db.realm")
var config = Realm.Configuration.defaultConfiguration
config.fileURL = realmUrl
Realm.Configuration.defaultConfiguration = config
This works. But my coding to read from Realm, which was working before that, now crashes with the exeption:
This was working up to that change: `let realm = try! Realm()``
But now it creates this beautiful error ;-)
fatal error: 'try!' expression unexpectedly raised an error: Error Domain=io.realm
Code=2 "Operation not permitted" UserInfo={Error Code=2,
NSFilePath=/private/var/mobile/Containers/Shared/AppGroup/4E8402AD-89E4-4138-8B83-CA6B409BB238,
Underlying=n/a, NSLocalizedDescription=Operation not permitted}:
file /Library/Caches/com.apple.xbs/Sources/swiftlang/swiftlang-703.0.18.8/src/swift/stdlib/public/core/ErrorType.swift, line 54
I am a bit lost. Hopefully anybody can help me out. TIA John
Upvotes: 1
Views: 1061
Reputation: 18308
The problem is that the path fileURL
you're setting on Realm's configuration is the path to your app group container, not the path to a file within it. This is due to the following piece of the code:
let realmUrl: NSURL = NSFileManager.defaultManager().containerURLForSecurityApplicationGroupIdentifier("group.net.exchange.On")!
realmUrl.URLByAppendingPathComponent("db.realm")
NSURL.URLByAppendingPathComponent(_:)
returns a new URL rather than mutating the existing one. Changing the code to something like the following should result in the correct URL being set on the Realm's configuration:
let groupContainerUrl = NSFileManager.defaultManager().containerURLForSecurityApplicationGroupIdentifier("group.net.exchange.On")!
let realmUrl = groupContainerUrl.URLByAppendingPathComponent("db.realm")
Upvotes: 2