Encoding & Decoding
MBurgerSwift has a built in system that can be used to init your custom constructs. You have only to make your construct conform to MBDecodable protocol.
For example a News that's reflecting a newsfeed block in MBurger:
1
class News: MBDecodable {
2
let text: String
3
let images: [MBImage]
4
let link: String
5
let date: Date
6
โ€‹
7
enum DecoderCodingKeys: String, CodingKey {
8
case text
9
case images
10
case link
11
case date
12
}
13
โ€‹
14
required init(from decoder: MBDecoder) throws {
15
let container = try decoder.container(keyedBy: DecoderCodingKeys.self)
16
โ€‹
17
text = try container.decode(String.self, forKey: .text)
18
images = try container.decode([MBImage].self, forKey: .images)
19
link = try container.decode(String.self, forKey: .link)
20
date = try container.decode(Date.self, forKey: . date)
21
}
22
}
Copied!
And call the decode function of MBDecoder to create and populate an array of news like this:
1
MBClient.getSections(ofBlock: THE_BLOCK_ID, parameters: nil, elements: true, success: { (sections, _) in
2
sections.forEach { section in
3
do {
4
if let elements = section.elements {
5
let news = try MBDecoder.decode(News.self, elements: elements)
6
newsArray.append(news)
7
}
8
} catch let error {
9
self.showError(error)
10
}
11
}
12
}, failure: { error in
13
self.showError(error)
14
})
Copied!
The DecoderCodingKey needs to match to the name of the element in the MBurger block(e.g. if the element on the dashboard is called Title the decoder key needs to be Title):
1
enum DecoderCodingKeys: String, CodingKey {
2
case text = "Title"
3
case images
4
case link
5
case date
6
}
Copied!
You can find a complete example in the Example project.
Last modified 1yr ago
Copy link