CafeNomad — API Practice, JSON to Swift4 Conversion

Vince Lee
Vince Lee
Aug 26, 2017 · 2 min read

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.

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

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.

or try JSON to Swift auto transfer website:

Project Github:

彼得潘的 Swift iOS App 開發教室

學習 Swift iOS App 開發的學生作品集

)

Vince Lee

Written by

Vince Lee

彼得潘的 Swift iOS App 開發教室

學習 Swift iOS App 開發的學生作品集

Welcome to a place where words matter. On Medium, smart voices and original ideas take center stage - with no ads in sight. Watch
Follow all the topics you care about, and we’ll deliver the best stories for you to your homepage and inbox. Explore
Get unlimited access to the best stories on Medium — and support writers while you’re at it. Just $5/month. Upgrade