ram
ram

Reputation: 527

Fetch JSON, parse it into an array, and print it in Swift

I'm trying to fetch json data from an API, parse it into an array of struct, and print the array. But when I try to print it out, only a blank array is returned. I am trying to understand how to write code for asynchronous operations and am not sure where to go from here. Could someone please point me in the right direction? I'm trying this out on Playgrounds using Xcode 9, Swift 4.

import Foundation

struct Item: Decodable {
    var userId: Int?
    var id: Int?
    var title: String?
    var body: String?
}

var items = [Item?]()

let completionHandler = { (data: Data?, response: URLResponse?, error: Error?) in
        if error != nil {
            print("Error occured: \(error.debugDescription)")
        }
        
        let decoder = JSONDecoder()
        do {
            items = try decoder.decode([Item].self, from: data!)
            print(items)
        } catch {
            print("Error: Unable to fetch data")
        }
    }

func getJson() {
    let url = URL(string: "https://jsonplaceholder.typicode.com/posts")!
    let session = URLSession.shared
    let task = session.dataTask(with: url, completionHandler: completionHandler)
    task.resume()
    print(items)
}

getJson()

Upvotes: 0

Views: 95

Answers (1)

vadian
vadian

Reputation: 285072

To be able to run asynchronous stuff in a Playground you have to add

import PlaygroundSupport
PlaygroundPage.current.needsIndefiniteExecution = true

Three notes:

  1. The print line after resume is pointless. It will always print an empty array. The print line in the completion handler shows the real result
  2. Declare items as

    var items = [Item]()
    

    JSONDecoder() returns something non-optional or throws an error

  3. This particular API sends always all fields so you can even declare all struct members as non-optional

    struct Item: Decodable {
        var userId: Int
        var id: Int
        var title: String
        var body: String
    }
    

Upvotes: 0

Related Questions