Cannot get the latest CoreData DB file in Swift

I have built a app using CoreData for persisting contents. Everything works fine. Now I would like to export the SQLite DB file of my stored data.

I checked the DB file's path by downloading container from my device. It seems to be "~\Library\Application Support\MainData.sqlite".

Screenshot of filepath:

enter image description here

I called shareDatabase() to share DB file using AirDrop to my Mac, and it works normally:

func shareDatabase() {
    try? (UIApplication.shared.delegate as! AppDelegate)
    let fileName = "MainData.sqlite"
    let filePath = URL(fileURLWithPath: NSHomeDirectory()).appendingPathComponent("Library").appendingPathComponent("Application Support").appendingPathComponent(fileName)

    let activityVC = UIActivityViewController(activityItems: [filePath], applicationActivities: nil)
    present(activityVC, animated: true, completion: nil)

Strangely, the transferred MainData.sqlite is not the latest one, but the one with modified date of yesterday. I also used DB Browser opened the file. It does not contain the latest data.

Screenshot: info of AirDrop-shared file:

enter image description here

However, the MainData.sqlite from downloaded container is latest updated. The latest data are in this file, checking with DB Browser.

Screenshot: info of file in container:

enter image description here

Please help point out what is wrong with my codes.

1 answer

  • answered 2018-01-14 08:46 user2782993

    Try to use this:

    or this:

    Check this out:


    "Since iOS 7 and OS X 10.9 the default journalling mode in SQLite Stores is WAL. In addition to the main store file you’ll find a WAL file with the same (or larger) size as the store file, and a less important SHM file.

    Prior to this implementation it was easy to save the context, extract the store file and ship it with an app as a pre-made data store. That’s no longer possible, because by default all data changes are written to the WAL file and do not sync with the main store file.

    This is not a problem if you’re not shipping a pre-made store file with your app, but if you do, then this “improvement” has just ruined your way of delivering prewritten data stores.

    Lucky for us we can switch this entire WAL business off by passing an option when creating our NSPersistentStoreCoordinator."