Open and Close a Realm

To open a synced realm, call asyncOpen, passing in the user's Configuration object, which includes the partition name. The following code demonstrates this:

let app = App(id: YOUR_REALM_APP_ID)
// Log in...
let user = app.currentUser
let partitionValue = "some partition value"
var configuration = user!.configuration(partitionValue: partitionValue)
Realm.asyncOpen(configuration: configuration) { result in
switch result {
case .failure(let error):
print("Failed to open realm: \(error.localizedDescription)")
// handle error
case .success(let realm):
print("Successfully opened realm: \(realm)")
// Use realm

In the above example, the code shows how to open the realm realm asynchronously by using asyncOpen(). You can also open a realm synchronously by using one of the Realm() initializers. This works if the device is offline, but may lead to temporary data inconsistencies while the remote data is downloaded.

let realm = try! Realm(configuration: configuration)
print("Opened realm: \(realm)")

When opening a local (non-synced) realm, you pass a custom Configuration object that must not contain a SyncConfiguration object. The following example uses the fileURL and readOnly properties to open a readonly local realm with a specific file location:

// Open the default realm
let defaultRealm = try! Realm()
// Open the realm with a specific file URL, for example a username
let username = "GordonCole"
var config = Realm.Configuration.defaultConfiguration
let realm = try! Realm(configuration: config)

There is no need to manually close a realm in Swift or Objective-C. When a realm goes out of scope and is removed from memory due to ARC, the realm is closed.

Give Feedback