I'm working on a CarRental App for OS X in swift. I have a NSImageView where the user can drop a picture and some TextFields. The car data are stored in an array of Car Objects. I need to write this data to an SQLite database with FMDB. I have no problems with the text, but how to save the picture? The below code runs without error but it does not save the image correctely.
let sql = "INSERT INTO tblCars (cMakeModel, cPrice, cPhoto) VALUES (?,?,?)"
if let db = DBManager.openDB(dbName) {
for var i = 0; i < carsArray.arrangedObjects.count; ++i {
let car = carsArray.arrangedObjects[i] as CarData
let ok = db.executeUpdate(sql, withArgumentsInArray: [car.makeModel, car.price, car.photo!])
if !ok {
println("Error: \(db.lastErrorMessage())")
return
}
}
println("Car added")
}
How to save an Image with FMDB?
FMDB can save
NSDataobjects in SQLite as BLOBs. So, the only question is how to getNSDatarepresentation (e.g. PNG, JPEG, TIFF, etc.) of the image.If possible, one should use the original digital asset you used to create the
NSImagein the first place. For example, if you loaded it from a PNG or JPEG file, go back and get theNSDatafrom that file.If you only have a
NSImageobject, you can create a representation for that image. This generally not ideal because you often can make the asset bigger than it was originally and/or you can introduce quality loss.If you wanted to get a PNG representation of the image, though, you could do something like:
As Rajeev points out, if your images are large (i.e. not thumbnail sized) SQLite is poorly suited for storing large binary objects. So you might store the digital asset in the file system (e.g. in your app's sandbox) and then only store a relative reference to that file in the SQLite database.