8

Converting Data to String returns a nil value.

Code:

// thus unwraps the image
if let image = image{
        print("Saving image data")

    // don't unwrap here
        if let data = UIImagePNGRepresentation(image){ 
            let str = String(data: data, encoding: .utf8)

            print(str)

        }
    }

I don't know the reason. Also, how do I convert the String back to Data?

Fogmeister
  • 76,236
  • 42
  • 207
  • 306

1 Answers1

6

This doesn't work because when you interpret the bytes of the Image as a String, the string is invalid. Not every jumble of data is a valid utf8 string. i.e. not every collection of n bits (8, sometimes 16) are a valid utf8 code point. The Swift String api loops through the data object you pass it to validate that it is a valid string. In your case, theres no reason to think that this Data is a valid string, so it doesn't work.

A good read on utf8: https://www.objc.io/issues/9-strings/unicode/

Joe Daniels
  • 1,646
  • 1
  • 11
  • 9
  • 1
    You better use `base64` encoding to convert `Data` to `String`. – Ryan Dec 12 '16 at 23:49
  • How do I use base64 @Ryan –  Dec 12 '16 at 23:50
  • 3
    base 64 is a bad solution for this kind of thing. – Joe Daniels Dec 12 '16 at 23:55
  • Strings store readable text, where readable text is defined as a data conforming to a specification/encoding (like utf8/16, ascii, etc). Your image data obviously doesn't fit that definition. – Joe Daniels Dec 12 '16 at 23:58
  • images also do not belong in sqlite. base64 blows up the size by quite a bit leading to significant inefficiency, and databases (esp. sqlite) aren't designed to store blobs of unstructured data, they're designed to store tabular data. – Joe Daniels Dec 13 '16 at 00:00
  • It is a bad solution. But this app isn't for commercial reasons. It is for my homework. The professor does not care how I do it. –  Dec 13 '16 at 00:01
  • haha, understood... but the string api does care. I've tried this before, and I don't think there's any string encoding you can choose that will work in all cases. – Joe Daniels Dec 13 '16 at 00:03
  • 1
    Now That I have been developing for a while, I should have taken Ryan answer. The assignment was for school and base64 always does the trick. I hate stackoverflow because everyone over complicated everything. –  Jan 12 '18 at 13:35