Created
April 7, 2019 15:09
-
-
Save chamook/74e3857d1323677589380c9197b523da to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
struct RGB: Decodable { | |
var red: Int | |
var green: Int | |
var blue: Int | |
} | |
struct Colour: Decodable { | |
var id: String | |
var name: String | |
var hex: String | |
var rgb: RGB | |
} | |
struct Item: Decodable { | |
var id: String | |
var name: String | |
} | |
struct ColourWithItems { | |
var colour: Colour | |
var items: [Item] | |
} | |
private func loadColours() { | |
struct ColourDto: Decodable { | |
var colours: [Colour] | |
} | |
struct ItemDto: Decodable { | |
var items: [Item] | |
} | |
let myColoursUrl = URL(string: "http://localhost:8081/my-colours")! | |
var request = URLRequest(url: myColoursUrl) | |
request.setValue("application/json", forHTTPHeaderField: "Accept") | |
URLSession.shared.dataTask(with: request) { [weak self] (data, response, error) in | |
guard error == nil else { | |
print("Error getting colours") | |
return | |
} | |
guard let content = data else { | |
print("Couldn't get any colours") | |
return | |
} | |
do { | |
let colourData = try JSONDecoder().decode(ColourDto.self, from: content) | |
for colour in colourData.colours { | |
let itemsUrl = URL(string: "http://localhost:8082/items/\(colour.id)")! | |
URLSession.shared.dataTask(with: itemsUrl) { [weak self] (data, response, error) in | |
guard error == nil else { | |
print("Error getting items for \(colour.id)") | |
return | |
} | |
guard let content = data else { | |
print("Couldn't get any items for \(colour.id)") | |
return | |
} | |
do { | |
let itemData = try JSONDecoder().decode(ItemDto.self, from: content) | |
self?.colours.append(ColourWithItems(colour: colour, items: itemData.items)) | |
DispatchQueue.main.async { | |
self?.tableView?.reloadData() | |
} | |
} catch let err { | |
print("Error decoding item json", err) | |
} | |
}.resume() | |
} | |
} catch let err { | |
print("Error decoding colour json", err) | |
} | |
}.resume() | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment