matsuda
1/23/2017 - 8:22 AM

Realm utilities

Realm utilities

import RealmSwift

final class RealmHelper {
    class func migrate() {
        print("<<<<<<<<<<<<<<<<<<<< Realm migration start >>>>>>>>>>>>>>>>")
        do {
            try _ = masterRealm()
#if DEBUG
//            cleanUserRealm()
#endif
            try _ = userRealm()
        } catch {
            fatalError("Not complete Realm migration because \(error)")
        }
        print("<<<<<<<<<<<<<<<<<<<< Realm migration end   >>>>>>>>>>>>>>>>")
    }

    class func cleanUserRealm() {
        guard let url = UserRealm.configuration.fileURL else {
            return
        }
        cleanRealm(url: url)
    }

    class func cleanMasterRealm() {
        guard let url = MasterRealm.configuration.fileURL else {
            return
        }
        cleanRealm(url: url)
    }

    class func cleanRealm(url realmURL: URL) {
        print("Realm url : \(realmURL)")
        let realmURLs: [URL] = [
            realmURL,
            realmURL.appendingPathComponent("lock"),
            realmURL.appendingPathComponent("note"),
            realmURL.appendingPathComponent("management"),
        ]
        let fm = FileManager.default
        for url in realmURLs {
            do {
                try fm.removeItem(at: url)
                print("Realm remove \(url)")
            } catch {}
        }
    }

    class func installRealm(url realmURL: URL) throws {
        print("Install master realm")
        print("Realm url : \(realmURL)")
        let realmPath = realmURL.path

        let fm = FileManager.default
        if fm.fileExists(atPath: realmPath) { return }
        guard let resourcePath = Bundle.main.resourcePath else { return }

        let path = (resourcePath as NSString).appendingPathComponent(realmURL.lastPathComponent)
        do {
            try fm.copyItem(atPath: path, toPath: realmPath)
            print("Copy from \(path) to \(realmPath)")
        } catch (let error) {
            print("Can't copy from \(path) to \(realmPath).")
            throw error
        }
    }
}
import RealmSwift

public extension Realm {
    func truncate<T: Object>(type: T.Type) {
        delete(objects(type))
    }

    func empty<T: Object>(type: T.Type) -> Results<T> {
        return objects(type).empty()
    }
}

public extension Results {
    func empty() -> Results<T> {
        return filter("FALSEPREDICATE")
    }
}
import RealmSwift

func masterRealm() throws -> Realm {
    return try MasterRealm.realm()
}

enum MasterRealm {
    static func realm() throws -> Realm {
        return try Realm(configuration: configuration)
    }

    static var configuration: Realm.Configuration {
        let objectTypes: [RealmSwift.Object.Type] = [
            Foo.self,
        ]

        let migrationBlock: RealmSwift.MigrationBlock = { migration, oldSchemaVersion in
            print("master migration block ")
            // 初期データファイルコピーのためのダミーマイグレーション
            if oldSchemaVersion < 1 {}
            print("master migration complete.")
        }

        return Realm.Configuration(
            fileURL: fileURL,
            schemaVersion: UInt64(schemaVersion),
            migrationBlock: migrationBlock,
            objectTypes: objectTypes
        )
    }

    private static var fileURL: URL {
        let path = NSSearchPathForDirectoriesInDomains(.documentDirectory,
                                                       .userDomainMask, true).first!
        return URL(fileURLWithPath: path).appendingPathComponent(filename)
    }

    private static var filename: String { return "master.realm" }

    private static var schemaVersionInfoKeky: String { return "Master Realm Schema Version" }

    private static var schemaVersion: Int {
        guard let version = Bundle.main.infoDictionary![schemaVersionInfoKeky] as? Int else {
            fatalError("Not found '\(schemaVersionInfoKeky)' in Info.plist")
        }
        return version
    }
}
import RealmSwift

final class Foo: Object {
    dynamic var code: String = UUID().uuidString
    dynamic var timestamp: Date = Date()

    override static func primaryKey() -> String? {
        return "code"
    }

    override static func indexedProperties() -> [String] {
        return ["timestamp"]
    }
}

extension Results where T: Foo {
    func lately() -> Results<T> {
        return sorted(byKeyPath: "timestamp", ascending: false)
    }

    func by(code: String) -> Results<T> {
        let predicate = NSPredicate(format: "code = %@", code)
        return filter(predicate)
    }
}