Learn Courses My Dashboard

Parsing JSON from web source

I completed the Recipe List app and successfully modified the code to parse a local JSON file and display the data in my desired VStack. My actual data will be on the web, and I’m having trouble returning my parsed data. The modified Recipe List code is shown below.

class dataService2 {
    func getLocalData2() -> [grid] {
        if let url = URL(string: "http:// - myServer - /data2.json") {
            URLSession.shared.dataTask(with: url) { data, response, error in
                if let data = data {
                   do {
                      let gridData = try JSONDecoder().decode([grid].self, from: data)
                    for r in gridData {
                        r.id = UUID()
                   *** return gridData ***
                   catch let error {
        return [grid]()

My ‘return gridData’ (noted with *** x *** here) in the do generates an error ‘Unexpected non-void return value in void function’. It seems I need to use a completion handler since URLSession is an async function, but this is beyond my knowledge at the moment. Any help or guidance would be greatly appreciated!

*Note I’m using Swift 4 / Xcode 12.4, so async - await is not an option for me.

You’ll need to use a completion handler (closure) for returning the code out of the data task because yes URLSession.shared.dataTask does not return a value

Correct, do you have a good example for my application? As stated this is beyond my capability at the moment and this is my only issue to finish this project.

Searching “fetch json swift dataTask”

This article came up, which shows one way of doing this