Code:
import SQLite
import SwiftUI
class CoreDataViewModel: ObservableObject {
private var db: Connection?
@Published var allEntries: [String] = []
@Published var searchResults: [String] = []
init() {
copyDatabaseIfNeeded()
openDatabase()
fetchAllEntries()
}
deinit {
closeDatabase()
}
private func openDatabase() {
do {
let documentsURL = try FileManager.default.url(for: .documentDirectory, in: .userDomainMask, appropriateFor: nil, create: false)
let finalDatabaseURL = documentsURL.appendingPathComponent("english_grammar_today.db")
db = try Connection(finalDatabaseURL.path)
print("Successfully opened connection to database at \(finalDatabaseURL)")
} catch {
print("Unable to open database. Verify that you copied the database file to the documents directory.")
}
}
private func closeDatabase() {
db = nil
print("Successfully closed connection to database")
}
func searchInDatabase(for keyword: String) {
guard !keyword.isEmpty else {
// If the keyword is empty, show all entries
searchResults = allEntries
return
}
do {
let query = "SELECT entry FROM dictionary WHERE entry LIKE ?"
searchResults = try db?.prepare(query + " ?", ["%" + keyword + "%"]).map { $0[0] as? String ?? "" } ?? []
} catch {
print("Error searching in database: \(error)")
}
}
func fetchAllEntries() {
do {
let query = "SELECT entry FROM dictionary"
allEntries = try db?.prepare(query).map { $0[0] as? String ?? "" } ?? []
} catch {
print("Error fetching all entries: \(error)")
}
}
func copyDatabaseIfNeeded() {
// Move database file from bundle to documents folder
let fileManager = FileManager.default
guard let documentsUrl = fileManager.urls(for: .documentDirectory, in: .userDomainMask).first else { return }
let finalDatabaseURL = documentsUrl.appendingPathComponent("english_grammar_today.db")
do {
if !fileManager.fileExists(atPath: finalDatabaseURL.path) {
print("DB does not exist in documents folder")
if let dbFilePathPath = Bundle.main.path(forResource: "english_grammar_today", ofType: "db") {
try fileManager.copyItem(atPath: dbFilePath, toPath: finalDatabaseURL.path)
} else {
print("Uh oh - english_grammar_today.db is not in the app bundle")
}
} else {
print("Database file found at path: \(finalDatabaseURL.path)")
}
} catch {
print("Unable to copy foo.db: \(error)")
}
}
}
**DB does not exist in documents folder**
**Uh oh - foo.db is not in the app bundle**
**Successfully opened connection to database at file:///Users/howiema/Library/Developer/CoreSimulator/Devices/E49EA14F-17E0-4F09-8235-2F7F5835095F/data/Containers/Data/Application/46FA47A0-B2DE-4A9C-9346-5DD2B01C6F97/Documents/english_grammar_today.db**
**Error fetching all entries: no such table: dictionary (code: 1)**
After I clicked to run the program, I realized that the table dictionary does not exist… And I dunno why…
The link is picture, Why the db file is 0 byte??
I want to copy the db file to that device file path, containing the structure and data




