How do I get my pre-populated Default.realm file onto a device?

孤者浪人 提交于 2019-12-24 04:23:25

问题


I have a realm file that is already populated with data that needs to be there when the app is loaded on a device.

What can I do to get the realm file onto my device for testing and what do I need to do to make sure it is already there when someone downloads the app from the app store?

I am using Swift.


回答1:


Add your database file to the Xcode project, i.e. "preloaded.realm" Make sure you select the add to targets, when first dropping in your file

Then (taking from the migration example) you can do something like this to copy that preloaded file to your default directory. This will create a read/write realm

// copy over old data files for migration
let defaultPath = RLMRealm.defaultRealmPath()
let defaultParentPath = defaultPath.stringByDeletingLastPathComponent

let v0Path = NSBundle.mainBundle().resourcePath!.stringByAppendingPathComponent("preloaded.realm")
NSFileManager.defaultManager().removeItemAtPath(defaultPath, error: nil)
NSFileManager.defaultManager().copyItemAtPath(v0Path, toPath: defaultPath, error: nil)

Here is a link to that general code https://github.com/realm/realm-cocoa/blob/master/examples/ios/swift-2.2/Migration/AppDelegate.swift




回答2:


You'll first have to create the realm file you want to ship with your app. Once you have that, add it to your app's Xcode project and copy it into the bundle (which Xcode should do automatically).

At this point, the app should be able to access the bundled file (you can use NSBundle.mainBundle().pathForResource(_:ofType:) to get the path).

You can either create a read-only realm at this path (see RLMRealm(path:readOnly:error:)), or copy it to your Documents directory to create a read-write realm file.

You should refer to our migration example for more details on how to do this.



来源:https://stackoverflow.com/questions/27534123/how-do-i-get-my-pre-populated-default-realm-file-onto-a-device

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!