CafeNomad — API Practice, JSON to Swift4 Conversion

Hello every digital workers, if you in love with working in small coffee shop or having a good time, here is a website called Cafe Nomad which collects over 1,700 indie coffee shops in Taiwan. Check it out in the link below.

Things will learned

1. loading file from web service

Try to find any API from https://github.com/toddmotto/public-apis, and get the url that will show you JSON file.

URLSession helps loading images or heavy data in the background.

var shopsName: [String] = []override func viewDidLoad() {super.viewDidLoad()let urlStr = “https://cafenomad.tw/api/v1.2/cafes/taipei"let url = URL(string: urlStr!)let task = URLSession.shared.dataTask(with: url!) { (data, response, error) in

2. JSON structure convert to swift

There is plenty of ways to transform JSON, here is a more of an old way to do it since the JSON structure this time is simple (https://cafenomad.tw/api/v1.2/cafes/taipei).

To be short it’s like:

[ {name: Vince, pet: cat}, {name: Tony, pet: fish} ]

One array built up with several dictionaries.

Here is the code in swift:

if let data = data, let dic = (try? JSONSerialization.jsonObject(with: data, options: [])) as? [[String: Any]] {// URLSession in background loading queue so need (DispatchQueue.main) make it to main queueDispatchQueue.main.async{for shop in dic {self.shopsName.append(shop[“name”] as! String)} } } }task.resume()}

Finally shopName now is an array lined up with all the coffee shops and we could use the array to display in the title of you tableViewCell.

3. But things may changed, every JSON has it’s own structure, then you can learn from:

or try JSON to Swift auto transfer website:

Project Github:

--

--