Encio Peter
Encio Peter

Reputation: 329

Passing/Export core data database from one device to another

I'm trying to create an app which will store data locally using coredata. Then I want to share/export that data(from coredata) to be used by other devices using same app.

Is it possible to send a coredata from one device to another? Can I just copy the *.sqlite file and overwrite the coredata in the other device?

I saw this post how to export Core Data to CSV that allow core data to be exported as csv, But what I'm trying to achieve is to pass core data itself.

Thank You!

Upvotes: 4

Views: 4935

Answers (2)

Carlos Eduardo Millani
Carlos Eduardo Millani

Reputation: 347

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.

Upvotes: 3

Joony
Joony

Reputation: 4698

You can use migratePersistentStore:toURL:options:withType:error: of NSPersistentStoreCoordinator to save the store to a file. Once you have the file you can copy it to the other devices.

Other solutions might include iCloud if you're wanting data synchronisation.

Upvotes: 5

Related Questions