How to set .realm file on realm

谁都会走 提交于 2019-12-08 12:18:29

问题


I'm developing an app using realm. then I want to initialize realm by a set .realm file on the app. It is initially on /Users/*****/Library/Developer/CoreSimulator/Devices/~****~/Documents/default.realm/ I want the default.realm file on the app folder aligned with storyboard and ViewController.swift and other files. How can I solve this?


回答1:


You can pass a fileURL in the Realm init method

let config = Realm.Configuration(
    // Get the URL to the bundled file
    fileURL: Bundle.main.url(forResource: "MyBundledData", withExtension: "realm"),
    // Open the file in read-only mode as application bundles are not writeable
    readOnly: true)

// Open the Realm with the configuration
let realm = try! Realm(configuration: config)

See the documentation for more information. There are more things you can configure here too.

Important note: See the comment in the code above:

Open the file in read-only mode as application bundles are not writeable

To have the realm file sitting in your bundle, you would not be able to write to it, it would be read only. If you want to ship a pre-filled database with your app you can do this in your bundle but if you want it to be writeable you would need to copy it to the documents directory of your app on first launch and then use the version in that directory instead.

resources/files that you add in xcode and include in the 'copy bundle resources' in the build settings are included in your bundle. The bundle is not writeable. To ship a file with your app that you need to be writeable would need to be moved to a suitable folder. usually the app documents folder.



来源:https://stackoverflow.com/questions/50459785/how-to-set-realm-file-on-realm

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