用于单元测试路径权限的Realm文件(Xcode,Swift)



如果有类似的问题,请原谅我。我试着找到了,但找不到

嗨,伙计们,我在为我的单元测试运行Realm文件时遇到问题

所以我已经将领域文件移到了我的项目测试文件夹中

SampleAppTest
+ SampleAppTest.swift
+ SampleRealm.realm

我可以成功地定位领域文件,然而,当我试图实例化领域连接时,它给了我一个错误,说

Please use a path where your app has read-write permissions.

let bundle = Bundle(for: type(of: self))
if let path = bundle.path(forResource: "SampleRealm", ofType: "realm") {
let realmLocationURL = URL(string: path)

let realmVersion: UInt64 = 1
let config = Realm.Configuration(fileURL: realmLocationURL, schemaVersion: realmVersion, migrationBlock: { migration, oldSchemaVersion in
if (oldSchemaVersion < realmVersion) {}
}
)
let realm = try! Realm(configuration: config) // throws error
}
else {
print("path not found")
}

Folder access in Finder -> Get Info -> Read & Write

所以,一般来说,我可以把我的应用程序有读写权限的文件放在哪里?是否有一种可能的方法将其放入项目中,以便克隆项目的其他团队成员也可以使用相同的领域文件运行测试?谢谢

将Realm存储在您的应用程序捆绑包中使其成为只读领域,所以我认为这不是目的。

Realm用于Realm文件的默认位置总是一个不错的选择——然而,它不会与您的项目文件一起传播。

在开发过程中,我们经常将领域文件与项目一起存储——这样,如果项目被压缩、发送或共享(或放在dropbox上(,文件总是可用的,并且是可读写的。这里有一些代码可以做到这一点:

func gGetRealm() -> Realm? {
do {
let fileUrl = URL(fileURLWithPath: #file)
let projectSubUrl = fileUrl.deletingLastPathComponent() //the project files folder
let projectUrl = projectSubUrl.deletingLastPathComponent() //the project folder
let realmURL = projectUrl.appendingPathComponent("default.realm")
var config = Realm.Configuration.defaultConfiguration
config.fileURL = realmURL
let realm = try Realm.init(configuration: config)
return realm
} catch let error as NSError { //just throw the error to the console
print("Error!")
print("  " + error.localizedDescription)
let err = error.code
print(err)
let t = type(of: err)
print(t)
return nil
}
}

这是一个全局函数,用于将Realm存储在项目文件中-使用

guard let realm = gGetRealm() else { return }
let results = realm.objects(MyObject.self)

最新更新