Compress Realm file


#1

I have the following function that I’m calling once in my appDelegate.swift (in application didFinishLaunchingWithOptions)

private func setupDefaultRealm() {
        NSLog("\(#function) | Default Realm Starts")
        do {
            let fileURL = try FileManager.default.url(for: .documentDirectory, in: .userDomainMask, appropriateFor: nil, create: false).appendingPathComponent("main-tocca.realm")
            let realmConfig = Realm.Configuration(fileURL: fileURL, readOnly: false, schemaVersion: 4, migrationBlock: { (migration, oldSchemaVersion) in
                NSLog("\(#function) | Migration")
                if oldSchemaVersion < 4 {
                    NSLog("\(#function) | Migration to version 4")
                    migration.enumerateObjects(ofType: Source.className()) { (_, newSource) in
                        newSource?["fileName"] = ""
                    }
                }
            }, deleteRealmIfMigrationNeeded: true, shouldCompactOnLaunch: { (totalBytes, usedBytes) -> Bool in
                // totalBytes refers to the size of the file on disk in bytes (data + free space)
                // usedBytes refers to the number of bytes used by data in the file
                
                // Compact if the file is over 100MB in size and less than 50% 'used'
                let oneHundredMB = 100 * 1024 * 1024
                return (totalBytes > oneHundredMB) && (Double(usedBytes) / Double(totalBytes)) < 0.5
            })
            
            Realm.Configuration.defaultConfiguration = realmConfig
            
            autoreleasepool {
                do {
                    // Realm is compacted on the first open if the configuration block conditions were met.
                    _ = try Realm(configuration: realmConfig)
                } catch {
                    NSLog("\(#function) | Realm Error: \(error.localizedDescription)")
                    SentryEventReportManager.report(err: error)
                }
            }
        } catch {
            NSLog("\(#function) | Realm File Error: \(error.localizedDescription)")
            SentryEventReportManager.report(err: error)
        }
    }

It seems that the compression process can take some time and the above code is not properly protecting me from reaching another point in my code where I call db = try! Realm() and crash.

Questions:

  1. Is the above code still correct (I took it from the documentation)
  2. Is there a way to make sure that Realm is fully compressed before continuing (I was thinking at using semaphore, but there might be a better option).

Thanks