Skip to content

Instantly share code, notes, and snippets.

@jpsim

jpsim/docs.md Secret

Created February 23, 2016 07:18
Show Gist options
  • Save jpsim/b976f546c5b4bf6231c3 to your computer and use it in GitHub Desktop.
Save jpsim/b976f546c5b4bf6231c3 to your computer and use it in GitHub Desktop.
NSFileProtection Realm

Using Realm with Background App Refresh

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.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment