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.

4
  • Is that a real sample of the JSON from your API? Commented Apr 14, 2016 at 5:22
  • it has a few fields before it but all I need to figure out is how to convert the data array of bytes to NSData Commented Apr 14, 2016 at 5:33
  • Assuming that these are decimal values, this does not look like base64 data. Commented Apr 14, 2016 at 5:55
  • This is how my blob returns the data Commented Apr 14, 2016 at 6:13

2 Answers 2

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)
Sign up to request clarification or add additional context in comments.

4 Comments

What do you mean by encoded string. All I have is a data array with bytes. That is what my API returns to me
Isn't the content of your array a string representation of the base 64 encode image?
No my API stores the encoded base 64 string as a BLOB but blobs return the data as a byte array
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 stackoverflow.com/questions/11860830/byte-array-to-nsdata
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)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.