Search code examples
iosswiftrealmnsfilemanager

Setting location of Realm in Swift


I have read the Realm docs and used this answer to try and set the location of Realm to the Application Support folder rather than the Documents folder.

My app requires an export of a file from the Documents folder so I can't users see the realm stuff in there too.

I'm using this code :

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!)

... in an attempt to place realm and all its files etc in the applicationSupportDirectory But it's not working at all, other than when I print out the location it appends the application support bit at the end of the location like this...

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

Which is useless.

I've tried looking for a simple guide on how to actually specify the location of realm in Swift 4 but can't find anything other than the answer I've listed. What am I doing wrong here?


Solution

  • 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!)