1

My IOS app is retrieving a JSON Object containing a field "file" which is an image. This field is encoded by the server in Base 64

JSON Serialization: Optional({
file = "/9j/4AAQSkZJRgABAQAAAQABAAD/........

I would need to load this field in an UIImageView. I tried multiple ways without any success. here is an extract of my code:

        let task = session.dataTaskWithRequest(request, completionHandler: { (data: NSData?, response: NSURLResponse?, error: NSError?) -> Void in
        if (error == nil) {

            let json: AnyObject?
            let imageArray: NSData?
            do{
            try json = NSJSONSerialization.JSONObjectWithData(data!, options: [])
                imageArray = json!["file"] as? NSData
                print("JSON file: \(imageArray)")

            }
        catch
        {
            print("error Serialization")
            return
        }

but imageArray is nil...any idea how I can retrieve this field (Base 64 Byte array) and convert it in an UIImage ?

1 Answer 1

4

JSON cannot contain binary data. It can only contain Strings, Numbers, Booleans and Nulls. You need to convert the base64 String to NSData yourself.

Replace the line imageArray = json!["file"] as? NSData to the following 5 lines.

if let fileBase64 = json!["file"] as? String {
    imageArray = NSData(base64EncodedString: fileBase64, options: [])
} else {
    print("missing `file` entry")
}
Sign up to request clarification or add additional context in comments.

8 Comments

ok, and how can I convert imageArray to UIImage ? I tried self.ordoPhoto.image = UIImage(data: imageArray!) but it doesn't work.
Clarify what you mean with "it doesn't work"? Does it generate a build-time error? Causes your app crash? or always nil or something other?
sorry for being unclear....my UIImageView ordoPhoto remains blank....even if I copy my imageArray by using self.ordoPhoto.image = UIImage(data: imageArray!)
Check if imageArray is nil or not.
it is not, I can print it, the content is finally there
|

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.