How to store and fetch images in SQLite and in what format the images get saved? It would be more helpful if explained with an example.
You can also store your image directly as a BLOB, however it depends on which framework you use for SQLite access. In case you use SQLite.swift, then there is an option:
Set up a file SQLiteHelper.swift like that:
class SQLiteHelper{
var db: Connection!
let personsTable = Table("person")
let id = Expression("id")
let firstName = Expression("firstName")
let lastName = Expression("lastName")
let profileImage = Expression("profileImage")
let date = Expression("savedAt")
init() {
do{
let path = NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true).first!
let dbTemp = try Connection("\(path)/myDb.sqlite3") //Create db if not existing
self.db = dbTemp
}
catch {
print("Error info: \(error)")
}
}
public func insertData(firstNameVal: String,
lastNameVal: String,
profileImageVal: Data,
dateVal: Date){
do{
//Create a new table only if it does not exist yet
try db.run(personsTable.create(ifNotExists: true) { t in // CREATE TABLE "person" (
t.column(id, primaryKey: true) // "id" INTEGER PRIMARY KEY NOT NULL,
t.column(firstName) // "firstName" TEXT,
t.column(lastName) // "lastName" TEXT,
t.column(profileImage) // "profileImage" BLOB,
t.column(date) // "savedAt" DATETIME)
})
}
catch {
print("The new SQLite3 Table could not be added: \(error)")
}
do{
try db.run(personsTable.insert(firstName <- firstNameVal,
lastName <- lastNameVal,
profileImage <- profileImageVal,
date <- dateVal
))
}
catch {
print("Could not insert row: \(error)")
}
}
public func getData() -> [Person]{
var persons = [Person]()
do{
for row in try db.prepare(personsTable) {
let person: Person = Person(firstName: row[firstName],
lastName: row[lastName],
profileImage: row[profileImage],
savedAt: row[date])
persons.append(person)
}
}
catch {
print("Could not get row: \(error)")
}
return persons
}
Now create a file Person.swift and put the following struct inside of it:
import Foundation
struct Person: Identifiable {
var id = UUID()
var firstName: String
var lastName: String
var profileImage: Data
var savedAt: Date
}
In order to store data as a .png BLOB you would now basically do something like that:
var databaseHelper: SQLiteHelper = SQLiteHelper.init()
self.databaseHelper.insertData(firstNameVal: "yourFirstName",
lastNameVal: "yourLastName",
profileImageVal: yourImageView.pngData(),
dateVal: Date())
If you want to display the image later in another Imageview you would have to do this:
var persons = self.databaseHelper.getData()
let profileImage = UIImage(data: persons[0].profileImage)
let myImageView = UIImageView(image: profileImage)
I have saved the image as a .png because I want to use my database outside of iOS and therefore want to ensure compatibility. If you want you can also store your UIImage directly. You would roughly need to change it like that:
let profileImage = Expression("profileImage")
...
profileImageVal: yourImageView,
...
let myImageView = persons[0].profileImage
...
import Foundation
import UIKit
struct Person: Identifiable {
var id = UUID()
var firstName: String
var lastName: String
var profileImage: UIImage
var savedAt: Date
}
Note: SQLite.swift also supports lazy loading, which would probably make more sense in ascenario like that...