在 Swift 中设置 Realm 的位置

Setting location of Realm in Swift

我已阅读 Realm 文档并使用 尝试将 Realm 的位置设置为 Application Support 文件夹而不是 Documents 文件夹。

我的应用程序需要从 Documents 文件夹中导出一个文件,因此我无法让用户也看到其中的领域内容。

我正在使用此代码:

var config = Realm.Configuration()

    config.fileURL = (FileManager.default.urls(for: .applicationSupportDirectory, in: .userDomainMask).first)

    // set the location
    Realm.Configuration.defaultConfiguration = config
    print (Realm.Configuration.defaultConfiguration.fileURL!)

...试图将领域及其所有文件等放置在 applicationSupportDirectory 中但它根本不起作用,除了当我打印出它在位置末尾附加应用程序支持位的位置时这...

.../Application/964D53C2-C880-4144-B5F0-688213820A67/Library/Application%20Support

没用。

我曾尝试寻找有关如何在 Swift 4 中实际指定领域位置的简单指南,但除了我列出的答案外找不到任何其他内容。我在这里做错了什么?

问题是您将 url 传递给一个目录,但它似乎期望 url 传递给一个文件。基于 docs 你应该可以做到这一点。

config.fileURL = FileManager.default
    .urls(for: .applicationSupportDirectory, in: .userDomainMask)
    .first
    .appendingPathComponent("default.realm")

try this code tested & working. we need to create Application Support directory it's not created by default.

    let fileManager = FileManager.default
    var config = Realm.Configuration()

    let urls = fileManager.urls(for: .applicationSupportDirectory, in: .userDomainMask)

    if let applicationSupportURL = urls.last {
        do {
            try fileManager.createDirectory(at: applicationSupportURL, withIntermediateDirectories: true, attributes: nil)
            config.fileURL = applicationSupportURL.appendingPathComponent("demo.realm")
        } catch let err {
            print(err)

        }
    }

    // Set this as the configuration used for the default Realm
    Realm.Configuration.defaultConfiguration = config

    print (Realm.Configuration.defaultConfiguration.fileURL!)

我的版本

// File Manager
let fileManager = FileManager.default

do {
    // Document directory URL
    let documentsDirectory = try fileManager.url(for: .documentDirectory, in: .userDomainMask, appropriateFor: nil, create: false)
    
    // Create App folder
    try fileManager.createDirectory(at: documentsDirectory.appendingPathComponent("app.folder/"), withIntermediateDirectories: true, attributes: nil)

} catch {
    print("Catch error")
}

// Configuring a Local Realm
var config = Realm.Configuration()

// Use the default directory, but add the app folder with the default realm file
config.fileURL = config.fileURL?.deletingLastPathComponent().appendingPathComponent("app.folder/default.realm")

// Set this as the configuration used for the default Realm
Realm.Configuration.defaultConfiguration = config

// Now print default Realm data base url
print(Realm.Configuration.defaultConfiguration.fileURL!)