This blog post suggests a good way to export the database as one file. Besides using the migratePersistentStore:toURL:options:withType:error:
method, it also creates a copy of the NSPersistentStoreCoordinator
to keep the current database consistent, and disables the sqlite write ahead and log to reduce all database to just one file.
In the device receiving the sqlite file, the following worked fine for me:
1 - Save the URL of the persistent store (persistentContainer.persistentStoreDescriptions.first?.url
)
2 - Delete the current persistent store, calling persistentStoreCoordinator.remove
on your store instance inside persistentStoreCoordinator.persistentStores
3 - Saving the new database in the URL of the old one, using FileManager.default.replaceItem
with the URL saved on the first step and the received file.
4 - Call persistentStoreCoordinator.addPersistentStore
to add the store to the list of stores that core data will manage.
Also, before executing this whole process it might be good to reset all contexts (context.reset) to ensure no reference was kept, and in my case I executed everything inside the persistentStoreCoordinator.performAndWait
method to avoid concurrency problems.