I'm trying to insert about 3 thousand string data into my app upon first launch. The problem I'm having is the inserting part is taking too long around 15-20secs. I looked up on ways to make it faster which the isTransaction method comes up, but I have no idea how to use it. I tried many examples online but doesn't seem to fit my situation very well. Help would be very much appreciated.
func insertWordData() {
if openDatabase() {
if let path = Bundle.main.path(forResource: "messagesToRead", ofType: "json") {
var query = ""
do {
let data = try Data(contentsOf: URL(fileURLWithPath: path), options: .alwaysMapped)
let jsonObj = JSON(data: data)
if jsonObj != JSON.null {
for (_, jsonObj) in jsonObj {
let WordString = jsonObj["FIELD1"]
let WordDefinition = jsonObj["FIELD2"]
query += "insert into words (\(field_WordID), \(field_WordString), \(field_WordDefinition)) values (null, '\(WordString)', '\(WordDefinition)');"
}
}
if !database.executeStatements(query) {
print("Failed to insert initial data into the database.")
print(database.lastError(), database.lastErrorMessage())
}
else {
//print(words)
}
} catch let error {
print(error.localizedDescription)
}
} else {
print("Invalid filename/path.")
}
database.close()
}
}
Nevermind, the problem was fixed all i had to do was add database.beginTransaction() before the for loop and database.commit() before database.close(). The speed went from 15-20secs to 0.5sec