Search code examples
iosdatabasesandbox

How to put DB in Sandboxed area in iOS App and access the path?


now, I have DB Data being used on Linux and Window.

I'd like to put it in the iPhone, and use them in my iOS Application.

How to put DB in Sandbox area of ​​my iOS Application ?? And where is the path?


Solution

  • Generally you’d use FileManager method url(for:in:appropriateFor:create:) to build a file URL:

    let fileURL = try! FileManager.default
        .url(for: .applicationSupportDirectory, in: .userDomainMask, appropriateFor: nil, create: true)
        .appendingPathComponent("test.sqlite")
    

    So, if you had a blank database in your bundle, you’d copy that initial copy of the database to the above file URL, and then open it using this URL from that point on. Or if you were programmatically creating the database from scratch, you’d again use this resulting file URL.

    But don’t save this absolute path anywhere. Always build it programmatically like above.


    Note, historically we used to use the .documentsDirectory for things like this (and you’ll see lots of those sorts of answers lingering about on the web). But nowadays we would use the .applicationSupportDirectory. See iOS Standard Directories: Where Files Reside document or the iOS Storage Best Practices video.