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, ...]
}
}