我正在嘗試使用捆綁的領域文件而沒有成功。我知道我的領域文件已成功複製到我的應用程序的目錄中,但我無法讀取它。無法在路徑上打開領域
fatal error: 'try!' expression unexpectedly raised an error: "Unable to open a realm at path '/Users/…/Library/Developer/CoreSimulator/Devices/…/data/Containers/Data/Application/…/Documents/default-v1.realm'. Please use a path where your app has read-write permissions."
func fullPathToFileInAppDocumentsDir(fileName: String) -> String {
let paths = NSSearchPathForDirectoriesInDomains(.DocumentDirectory,NSSearchPathDomainMask.UserDomainMask,true)
let documentsDirectory = paths[0] as NSString
let fullPathToTheFile = documentsDirectory.stringByAppendingPathComponent(fileName)
return fullPathToTheFile
}
在didFinishLaunchingWithOptions
:
let fileInDocuments = fullPathToFileInAppDocumentsDir("default-v1.realm")
if !NSFileManager.defaultManager().fileExistsAtPath(fileInDocuments) {
let bundle = NSBundle.mainBundle()
let fileInBundle = bundle.pathForResource("default-v1", ofType: "realm")
let fileManager = NSFileManager.defaultManager()
do {
try fileManager.copyItemAtPath(fileInBundle!, toPath: fileInDocuments)
} catch { print(error) }
}
和設置配置用於默認域:
var config = Realm.Configuration()
config.path = fileInDocuments
Realm.Configuration.defaultConfiguration = config
let realm = try! Realm(configuration: config) // It fails here!!! :-)
由於文檔建議,我曾嘗試和打開它直接從束路徑設置readOnly
到true
Realm.Configuration
對象。我不確定這是否與Realm有關,或者我是否忽略了文件系統的某些內容......。我也嘗試將文件存儲在庫文件夾中。
Realm 0.97.0
Xcode Version 7.1.1
任何運氣嗎?我遇到了同樣的問題 –
@AndréCytryn,將文件權限更改爲讀/寫操作對我來說是個竅門:-)另外兩個答案也是值得您嘗試的有價值的東西。 – Fabio