John B. John B. - 1 year ago 58
iOS Question

Realm exception Error Domain=io.realm Code=2 "Operation not permitted"

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


realmUrl: NSURL = NSFileManager.defaultManager().containerURLForSecurityApplicationGroupIdentifier("")!

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,
Underlying=n/a, NSLocalizedDescription=Operation not permitted}:
file /Library/Caches/, line 54

I am a bit lost. Hopefully anybody can help me out. TIA John

Answer Source

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("")!

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("")!
let realmUrl = groupContainerUrl.URLByAppendingPathComponent("db.realm")