0

I am currently working on a project for school. I have written an API using Express connected to a mysql database. And now I am writing the iOS app. My problem is that I need to save profile pictures. So I saved the png data of the picture into a **LONGBLOB** into db and I want to recreate the image into a **UIImage**. To do that I am trying to convert the buffer into ```Data``` So, the API is returning a buffer created that way:
let buffer = Buffer.from(ppData.data, 'binary').toString('base64');

And on the iOS side I tried:

guard let data = dict["data"] as? Data else {return nil}

Where dict["data"] is the buffer returned by the API.
But it always enter into the "else" part. What am i doing wrong

Edit:
As what it was said in comments, I decoded the Base64 encoded string. Now the data are decoded but creating a UIImage from it, fails, without any details. What I tried is:

let image = UIImage(from: base64DecodedData)

For example:

guard let strData = dict["data"] as? String else {
     return nil
}
                                
guard let data = Data(base64Encoded: strData, options: .ignoreUnknownCharacters) else {
     return nil
}
                
guard let picture = UIImage(data: data) else {
     return nil
}

Thanks.
double-beep
  • 5,031
  • 17
  • 33
  • 41
  • So what does `dict["data"]` contain? Is it perhaps a Base64 encoded *string* that needs to be decoded first? Have a look at https://stackoverflow.com/q/19088231/1187415. – Martin R Jan 24 '21 at 16:05
  • `dict["data"]` as you guessed contains the Base64 encoded string. I looked at what you sent. Now I have the decoded data but the `UIImage(data: data)` returns also nil, and I have no idea how I can go further to have more details about what failed. – Julianit0w Jan 24 '21 at 19:19
  • `guard let base64String = dict["data"] as? String else {return nil}; guard let data = Data(base64Encoded: base64String); let image = UIImage(from: data)` ? – Larme Jan 25 '21 at 11:20
  • I also tried that way... – Julianit0w Jan 25 '21 at 15:07
  • And? What's wrong? Did any "return" got called? Which one? What about using options like that: https://stackoverflow.com/questions/65887113/unable-to-decode-base64string-to-uiimage-in-ios-swift-but-working-fine-in-androi/65887374#65887374 – Larme Jan 26 '21 at 10:34
  • I've edited the post, see the example. The last return is called, ```UIImage(data: data)``` is returning nil. – Julianit0w Jan 31 '21 at 00:41

1 Answers1

0

The mistake was not in the swift code part but in my API and database structure. After reading some MySQL and Node.js documentaion, I switched from LONGBLOB (which is totally oversized) to MEDIUMTEXT.

Also, in the API I was trying to create a buffer from binary data but not from a base64 string encoded data, so I removed this line:

let buffer = Buffer.from(ppData.data, 'binary').toString('base64');
double-beep
  • 5,031
  • 17
  • 33
  • 41