Realm Swift Bundle Data

╄→гoц情女王★ 提交于 2020-06-29 04:27:07

问题


I converted a csv file to a realm file and I want to use it in my app. This is my code atm:

func inLibrarayFolder(fileName: String) -> URL {
    return URL(fileURLWithPath: NSSearchPathForDirectoriesInDomains(.libraryDirectory, .userDomainMask, true)[0], isDirectory: true)
        .appendingPathComponent(fileName)
}


func copyPreBundleDataCompeletely() {
    let mainRealmUrl = inLibrarayFolder(fileName: "main.realm")
    let bundleUrl = Bundle.main.url(forResource: "treesFull", withExtension: "realm")!
    
    //After launch after fresh install (if main.realm never created)
    if (!FileManager.default.fileExists(atPath: mainRealmUrl.path)){
        //copy bundled data into writable location compeletely
        try! FileManager.default.copyItem(
            at: bundleUrl, to: mainRealmUrl)
        print(mainRealmUrl)
    }
}

During the first launch, it creates the new file, but the file is a bit different from the original:

original db copied db

the Tree object:

class Tree: Object {
    @objc dynamic var id: Int32 = 0
    @objc dynamic var br = ""
    @objc dynamic var nm1 = ""
    @objc dynamic var nm2 = ""
    @objc dynamic var nm3 = ""
    @objc dynamic var longitude = 0.0
    @objc dynamic var latitude = 0.0
 
//    override static func primaryKey() -> String? {
//        return "id"
//    }
    
}

It looks like I have 2 databeses in the new file, how can I access the second one with the data or how can I copy the file properly?

Also, whats gonna happen when I make the id to a primary key? Obviously I dont have a parameter like that in the original downloaded file, so I guess I will need to migrate the data somehow...


回答1:


When it comes to importing, the file being imported has to be in a very specific format along with a specific file name

Your Realm object name is Tree, so the imported file name needs to match

Tree.csv

along with that the first line of the file needs to match the classes property names, comma separated

id,br,nm1...

I would suggest creating a very small test file to import with 3-4 lines to get it working. Then, once you mastered that then import the big file.



来源:https://stackoverflow.com/questions/61463208/realm-swift-bundle-data

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