2017-06-05 28 views
2

我想在我的應用程序中實現Realm數據庫,我有一些預裝入數據的領域數據庫。我已經搜遍了很多堆棧溢出資源,但沒有得到任何成功。如何預裝'Realm'數據庫到iOS swift3?

到目前爲止,現在,我已經做了以下步驟:

  1. 複製境界文件到我的應用程序的包
  2. 在應用程序委託

    添加以下代碼:

    path = Bundle.main.path(forResource: "data", ofType: "realm") 
    var config = Realm.Configuration(fileURL: NSURL(fileURLWithPath:  path!)) 
    config.readOnly = true 
    
    // Open the Realm with the configuration 
    let realm = try! Realm(configuration: config) 
    

但這不起作用,請提供一些解決方案。

注意:我不想遷移我的數據庫。

在此先感謝

回答

3

的一段代碼下面的作品完美的我第一次發射我的應用程序的過程中加載預加載領域實例:

let defaultPath = Realm.Configuration.defaultConfiguration.fileURL?.path 
let path = Bundle.main.path(forResource: "default", ofType: "realm") 
if !FileManager.default.fileExists(atPath: defaultPath!), let bundledPath = path { 
    do { 
     try FileManager.default.copyItem(atPath: bundledPath, toPath: defaultPath!) 
    } catch { 
     print("Error copying pre-populated Realm \(error)") 
    } 
} 
+0

它爲我工作爲好,感謝回答。 –

+0

當我嘗試添加名爲'Person'的新模型時,它會被添加。但是當我在領域瀏覽器中打開它時,它只顯示了一個原本就存在的「醫學」模型。你有任何關於領域內進入什麼的想法? –

+0

你是否讓'realm = try! realm()'在if塊之後?你還把這個代碼放在哪裏?它應該在AppDelegate的'func應用程序(didFinishLaunchingWithOptions:)' –