Realm - Add file with initial data to project (iOS/Swift)
Implement this function openRealm
in AppDelegate and call it in
func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool {
...
openRealm()
return true
}
func openRealm() {
let defaultRealmPath = Realm.defaultPath
let bundleReamPath = NSBundle.mainBundle().resourcePath?.stringByAppendingPathComponent("default.realm")
if !NSFileManager.defaultManager().fileExistsAtPath(defaultRealmPath) {
NSFileManager.defaultManager().copyItemAtPath(bundleReamPath!, toPath: defaultRealmPath, error: nil)
}
}
It will copy your realm file that you bundled in the app to the default realm path, if it doesn't exist already. After that you use Realm normally like you used before.
There's also the Migration example that you talked about in Swift.
In Swift 3.0.1 you may prefer this:
let defaultRealmPath = Realm.Configuration.defaultConfiguration.fileURL!
let bundleRealmPath = Bundle.main.url(forResource: "seeds", withExtension: "realm")
if !FileManager.default.fileExists(atPath: defaultRealmPath.absoluteString) {
do {
try FileManager.default.copyItem(at: bundleRealmPath!, to: defaultRealmPath)
} catch let error {
print("error copying seeds: \(error)")
}
}
(but please be careful with the optionals)
Swift version 3, courtesy of Kishikawa Katsumi:
let defaultRealmPath = Realm.Configuration.defaultConfiguration.fileURL!
let bundleReamPath = Bundle.main.path(forResource: "default", ofType:"realm")
if !FileManager.default.fileExists(atPath: defaultRealmPath.path) {
do
{
try FileManager.default.copyItem(atPath: bundleReamPath!, toPath: defaultRealmPath.path)
}
catch let error as NSError {
// Catch fires here, with an NSError being thrown
print("error occurred, here are the details:\n \(error)")
}
}
And for those that need @pteofil's answer in Objective-c
- (void)openRealm {
NSString *defaultRealmPath = [RLMRealm defaultRealm].path;
NSString *bundleRealmPath = [[[NSBundle mainBundle] resourcePath] stringByAppendingPathComponent:@"default.realm"];
if(![[NSFileManager defaultManager] fileExistsAtPath:defaultRealmPath]) {
[[NSFileManager defaultManager] copyItemAtPath:bundleRealmPath toPath:defaultRealmPath error:nil];
}
}