On iOS 8 and above, files inside apps are automatically encrypted using NSFileProtection
whenever the device is locked.
If your app attempts to do any work involving Realm while the device is
locked and its parent directory isn't set to NSFileProtectionNone
, an open() failed: Operation not permitted
exception will be thrown.
To avoid this, it is necessary to ensure the NSFileProtectionNone
file protection
attribute is applied to both the Realm file itself and its auxiliary files.
Since the auxiliary files can sometimes be lazily created and deleted mid-operation, it is recommended
to apply the file protection attribute to the parent folder containing these Realm files to
ensure the attribute is properly applied to all of them.
let realm = try! Realm()
// Get our Realm file's parent directory
let folderPath = (realm.configuration.path! as NSString).stringByDeletingLastPathComponent
// Disable file protection for this directory
try! NSFileManager.defaultManager().setAttributes([NSFileProtectionKey: NSFileProtectionNone],
ofItemAtPath: folderPath)
If your app contains other files for which you don't want to disable protection, we recommended that these Realm files be moved to their own separate directory.