How to print the api response to the console? Xcode 14

626 Views Asked by At

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()
1

There are 1 best solutions below

0
aashir mubeen On

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()
}