My app manages data with Core Data. I would like to add an export and import function to the app.
The export seems to work so far (at least a .sqlite file is saved). However, when I want to import the file, it is only greyed out and I cannot select it. Do I need to change anything in the code? Or set the permission for accessing files in the app settings in XCode (if so, what do I have to select in the iOS target properties? I haven’t found anything suitable while looking)?
// export funktion
func exportDatabase(completion: @escaping (URL?) -> Void) {
let context = persistentContainer.viewContext
let storeCoordinator = persistentContainer.persistentStoreCoordinator
guard let store = storeCoordinator.persistentStores.first else {
completion(nil)
return
}
let exportURL = FileManager.default.temporaryDirectory.appendingPathComponent("BookCatalog.sqlite")
do {
try storeCoordinator.migratePersistentStore(store, to: exportURL, options: nil, withType: NSSQLiteStoreType)
completion(exportURL)
} catch {
print("Failed to export database: (error)")
completion(nil)
}
}
// import funktion
func importDatabase(from url: URL, completion: @escaping (Bool) -> Void) {
let storeCoordinator = persistentContainer.persistentStoreCoordinator
guard let store = storeCoordinator.persistentStores.first else {
completion(false)
return
}
do {
try storeCoordinator.destroyPersistentStore(at: store.url!, ofType: NSSQLiteStoreType, options: nil)
try storeCoordinator.replacePersistentStore(at: store.url!, destinationOptions: nil, withPersistentStoreFrom: url, sourceOptions: nil, ofType: NSSQLiteStoreType)
try persistentContainer.viewContext.save()
completion(true)
} catch {
print("Failed to import database: (error)")
completion(false)
}
}
Tried it with the Code above. But I cannot select a file when I try to import