0

I am deserializing JSON data from an API. Within the JSON object, there's a property called avatar which contains an image. I need to convert this into a UIImage. What would be the most effective approach?

do {
  let decoder = JSONDecoder()
  let decodedResponse = try decoder.decode([RawUser].self, from: data)
                        
  self.users = self.formatUsers(rawUsers: decodedResponse)
} catch {
  print("Can't parse JSON..")
  return
}

For now I have two different struct, one for decoding and another to store the modified avatar:

struct RawUser: Decodable {
    var _id: String
    var name: String
    var avatar: Buffer
}
struct User: Hashable {
    var _id: String
    var name: String
    var avatar: UIImage()
}

And the function formatUsers():

private func formatUsers(rawUsers: [RawUser]) -> [User] {
  var users: [User] = []
        
  for rawUser in rawUsers {
    users.append(User(
      _id: rawUser._id,
      name: rawUser.name,
      avatarUrl: rawUser.avatarUrl.data.count > 0 ? UIImage(data: Data(User.avatarUrl.data))! : UIImage(),
  }
        
  return users
}

Here's the JSON:

{
  "_id": "cd890j2f22f",
  "name": "John"
  "avatar": {
    "type": "Buffer",
    "data": [9, 1, 34, ...]
  }
}
neo
  • 1
  • 2
  • Please show the JSON you get, and explain how the image is encoded. – Sweeper Aug 30 '23 at 06:54
  • 1
    Unrelated: but prefer `.isEmpty` over `.count > 0` & `print("Can't parse JSON..")` should always print the caught error: `print("Can't parse JSON: \(error)")` – Larme Aug 30 '23 at 06:55
  • @Sweeper I updated the JSON. I don't have trouble to do the conversion of the image but i's under buffer format (JPG) – neo Aug 30 '23 at 06:58
  • The comments in [this question](https://stackoverflow.com/q/76998832/5133585) probably answers your question. – Sweeper Aug 30 '23 at 06:58
  • @Sweeper I don't have trouble converting the image but if it is possible to do this in one `struct` instead of two – neo Aug 30 '23 at 07:04
  • Ah I see, then "I need to convert this into a UIImage. What would be the most effective approach?" is quite misleading. – Sweeper Aug 30 '23 at 07:09
  • Indeed, my bad. Thanks for the link – neo Aug 30 '23 at 07:12

0 Answers0