2

I have json in below format which I am fetching from server and parsing using SwiftyJSON.

{
name: "Ganesh"
imageURL:"www.abc.com/image.png"
}

I am downloading image using below code :

do{
     let myData = try Data(contentsOf: url)
}catch{
     Print("error")
}

Note: "url" contains url from json which is converted from string to URL

I want to save this "myData" in same json above with different key and access the same in future.

I am trying to save myData in json using SwiftyJSON method :

responseJSON["image"] = try JSON(data: myData)

Error which I am receiving : "if Error while converting data into json The data couldn’t be read because it isn’t in the correct format."

I am not getting what is the problem? Image is present at that url. if I convert myData into UIImage and If I assign it on UIImageView I can see it.

Ganesh Pawar
  • 191
  • 1
  • 12
  • 1
    I guess that `JSON(data:)` awaits for a `Data` object representing JSON Stringified. Which is not your case. I guess you want to do https://stackoverflow.com/questions/39075043/how-to-convert-data-to-hex-string-in-swift ? Also, `Data(contentsOf:)` is sync, in main thread that will block your UI, use `URLSession`, or a third library: SDWebImage, KingFisher, erc. – Larme Jun 07 '18 at 09:59

1 Answers1

3

If you want to save an image in JSON, the best way would be to convert Data to Base64 string

if let base64encodedString =  myData.base64EncodedString(){
    responseJSON["image"] = base64encodedString
}

To restore image, try this

guard let base64encodedString = responseJSON["image"] as? String else { return }
guard let imageData = Data(base64Encoded: base64encodedString) else { return }
let image = UIImage(data: imageData)

Although Base64 - encoded images take approximately 33% more space than raw data, they are web and database safe - base64 strings contain neither control characters, nor quotes, and can be transferred as parameter in URL query strings.

mag_zbc
  • 6,801
  • 14
  • 40
  • 62