Reputation: 682
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
Upvotes: 8
Views: 4667
Reputation: 307
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)")
}
}
}
Upvotes: 8
Reputation: 7806
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.
Realm is using NSURL
for paths since version 0.99+. The sample code was changed accordingly.
Upvotes: 9