1

I am learning about API's and decided to practice using them by writing a simple function to call an api and print the response. The issues I am having is that the response is not printing to the console. I am also new to Swift but watched a couple of tutorials, which lead me to write this basic skeleton code.

import Foundation

struct Posts: Codable {
    let userId: Int
    let id: Int
    let title: String
    let body: String
}

func fetch() {
    guard let url = URL(string: "https://jsonplaceholder.typicode.com/posts") else {
        return
    }
    
    let task = URLSession.shared.dataTask(with: url) { data, response, error in
        guard let data = data, error == nil else {
            return
        }
        do {
            let posts = try JSONDecoder().decode(Posts.self, from: data)
            print(posts) //Doesn't print the response
        }
        catch {
            print(error)
        }
    }
    task.resume()
}

fetch()
User534t
  • 11
  • 3
  • If I use `[Posts].self` instead of `Posts.self` it seems to work for me. Are you running this in Swift Playgrounds? – MadProgrammer Oct 27 '22 at 03:37
  • Does it print an error ? – Pierre Oct 27 '22 at 03:54
  • Is one of the `print` getting called? If not, seeing the code, are you doing this in Playground or in a Command Line App ? if yes, the issue is that the code ends before the asynchrone completion gets called. Add `PlaygroundPage.current.needsIndefiniteExecution = true` before if you are in Playgrounds. – Larme Oct 27 '22 at 07:37

1 Answers1

3

func fetch() { guard let url = URL(string: "https://jsonplaceholder.typicode.com/posts") else { return }

    let task = URLSession.shared.dataTask(with: url) { data, response, error in
        guard let data = data, error == nil else {
            return
        }
        do {
           
            let posts = try JSONDecoder().decode([Posts].self, from: data)
            print(posts)
        }
        catch {
            print(error)
        }
    }
    task.resume()
}