2

I am using SQLite.swift and I want to insert an UIImage in a column of type 'blob'.

My table:

"CREATE TABLE IF NOT EXISTS " + TABLE_USER +
                    "(" +
                    COLUMN_ID + " INTEGER PRIMARY KEY, " +
                    COLUMN_NAME + " TEXT NOT NULL, " +
                    COLUMN_IMAGE + " BLOB" +
                    ");";

After choosing an Image from gallery using UIImagePickerController, I want to save it to my "image"-column in database. I guess I have to convert the UIImage to a byte array (that's the way I did it in java in another project), but I don't know how it works in swift. That's what I tried:

// convert image
let data = image!.pngData()! as NSData
let dataBytes = data.bytes

// prepare update statement 
let updateStatement = "UPDATE " + DatabaseHelper.TABLE_USER + " SET " +
DatabaseHelper.COLUMN_IMAGE + " = ? " +
" WHERE " + DatabaseHelper.COLUMN_ID + " = " + String(id)

// run statement
do {
   let statement = try dbConnection.prepare(updateStatement)
   try statement.run(dataBytes) // Error: Cannot convert value of type 'UnsafeRawPointer' to expected argument type 'Binding?'
} catch {
   print("Error...")
}

Does anybody know how to insert the image to blob column? Thanks a lot for your help!

Raspberry
  • 139
  • 1
  • 11
  • Isn't it better to store the image to disk and store a file URL to the image in the database? – Joakim Danielson Jan 17 '20 at 09:08
  • Where does `let data = image!.pngData()! as NSData` come from? – El Tomato Jan 17 '20 at 09:14
  • You need another field when you deal with blob data. – El Tomato Jan 17 '20 at 09:16
  • Thanks for your comments. @ Joakim: there are different reasons I need to store it in database. I already did the same in a android app and it's no problem. Isn't there any possibility to do it in swift? @ ElTomato: that was just something I read in a stack overflow question and that was the way I tried to convert my UIImage to a byte array... What do you mean with "another field"? – Raspberry Jan 17 '20 at 10:06
  • I did a lot of research and I don't think it's a duplicate. It is not recommended to store image as a string (as described in the accepted answer), many stack overflow answers recommend to store it in a blob column - but I don't know how to do it in swift. Nishad Aurora writes in the last comment of the accepted answer, that he solved his problem with using a blob. But he doesn't say how he got it done. – Raspberry Jan 18 '20 at 07:49
  • I totally agree, that your question is not a duplicate to the linked question. Sadly I can not reopen it. I answered the linked question instead, because I figured out how this works. – frankenapps May 07 '20 at 14:11

0 Answers0