Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Realm: How to get the current size of the database

Is there a Realm API method to get the current database size of my RealmSwift app using RealmSwift as data storage? So that I could display that information in the app itself (like statistic information).

Thanks in advance

John

like image 460
John B. Avatar asked Nov 24 '15 14:11

John B.


2 Answers

Updated version for Swift 3

func checkRealmFileSize() {
    if let realmPath = Realm.Configuration.defaultConfiguration.fileURL?.relativePath {
        do {
            let attributes = try FileManager.default.attributesOfItem(atPath:realmPath)
            if let fileSize = attributes[FileAttributeKey.size] as? Double {

                print(fileSize)
            }
        }
        catch (let error) {
            print("FileManager Error: \(error)")
        }
    }
}
like image 125
suleymancalik Avatar answered Sep 21 '22 12:09

suleymancalik


Realm's APIs doesn't offer such a method. But for these purposes, it seems to be sufficient to use Foundation's NSFileManager API.

let realm = …
let path = realm.configuration.fileURL!.path
let attributes = try! NSFileManager.defaultManager().attributesOfItemAtPath(path!)
let fileSize = attributes.fileSize()

Note though: the reported file size is not completely occupied by data. For performance reasons, Realm is acquiring more disk space beforehand. If you want the disk usage of the actual stored data, you would need to write a compacted copy first and could measure that, but this seems to be for the use-case of reporting it to an end-user rather misleading and would hit the performance.

Update:

Realm is using NSURL for paths since version 0.99+. The sample code was changed accordingly.

like image 38
marius Avatar answered Sep 17 '22 12:09

marius