3

When I get my JSON back from my API this is how it looks

{
  data:[
     100,
     80,
     105,
     99,
     etc
  ]

}

How do I take this array and turn it back into a base64 string, then NSData and finally UIImage. Here is what I have thus far.

let byteArray = todo["image"]["data"].arrayObject
var data = NSData(bytes: byteArray!, length: byteArray!.count)
var image = UIImage(data: data)

When printing the data it prints fine but returns nil for image.

ConnorB
  • 406
  • 5
  • 16

2 Answers2

1

Have you tried iterating throug the array and building a string from its elements, the use base64 encoding/decoding api to get back from string to NSData? Something like that(I'm writing from iPad so I can't check).

var encodedString=""
for smallString in byteArray {
   encodedString += String(smallString)
}
let data = NSData(base64EncodedString: base64Encoded, options: NSDataBase64DecodingOptions.IgnoreUnknownCharacters)
var image = UIImage(data: data)
Andrea
  • 26,120
  • 10
  • 85
  • 131
  • What do you mean by encoded string. All I have is a data array with bytes. That is what my API returns to me – ConnorB Apr 14 '16 at 04:56
  • Isn't the content of your array a string representation of the base 64 encode image? – Andrea Apr 14 '16 at 06:04
  • No my API stores the encoded base 64 string as a BLOB but blobs return the data as a byte array – ConnorB Apr 14 '16 at 06:12
  • For instance this is a piece of image base64 encoded: iVBORw0KGgoAA and this is a C byte array byte[] bytes = { 3, 10, 8, 25 }; check here http://stackoverflow.com/questions/11860830/byte-array-to-nsdata – Andrea Apr 14 '16 at 07:10
0
    let byteArray = todo["image"]["data"].arrayObject         
    let string = String(bytes: byteArray, encoding: .utf8)
    let encodedImageData = string
    let imageData = NSData(base64Encoded: encodedImageData!)
    let image = UIImage(data: imageData! as Data)
JoeZ
  • 1
  • 1