BLACK FRIDAY SALE: Save 50% on all my Swift books and bundles! >>

SOLVED: Can't fetch JSON data correctly

Forums > SwiftUI

Please, help! I worked only with very basic JSON's and have some troubles with this.

JSON (Valid):

      "title": "Winter",
      "coverImage": "",
      "isPremium": false,
      "isNewKit": true,
      "kitItems": [
          "number": 0,
          "beforeImageURL": "",
          "afterImageURL": "",
          "dngURL": ""


struct PresetKit: Codable, Hashable {
    let title: String
    let coverImage: String
    let isPremium, isNewKit: Bool
    let kitItems: [PresetKitItem]

struct PresetKitItem: Codable, Hashable {
    let number: Int
    let beforeImageURL, afterImageURL: String
    let dngURL: String


class ViewModel: ObservableObject {
    @Published var presets: [PresetKit] = []

    func fetch() {

        guard let url = URL(string: "") else {

        let task = URLSession.shared.dataTask(with: url) { [weak self] data, _, error in
            guard let data = data, error == nil else {

            //: Covert to JSON
            do {
                let presets = try JSONDecoder().decode([PresetKit].self, from: data)
                DispatchQueue.main.async {
                    self?.presets = presets
            catch {



An empty array as a result, but I don't know why. Please, help!


I wrote you an answer, then realized you CHANGED the JSON format! Had to delete my first response.

Have you reviewed HackingWithSwift videos on loading JSON?
Here's a great one. Consider adapting some of these techniques to your code.

Decoding JSON

This takes the JSON fetching and decoding code out of your ViewModel.

Additionally, the lastest version of Swift has updated methods for making HTTP requests to web services that might take a while to return results.

Take a look at this updated HackingWithSwiftUI video:

Loading Data from Wikipedia

Notice how this code doesn't use .resume() to initiate a web request. Instead, it uses the updated try await syntax.

Try adapting these techniques. Let us know if this worked for you.


@Obelix That's work for me! Thank you so much, I really appreciate it.


Save 50% in my Black Friday sale.

SAVE 50% To celebrate Black Friday, all our books and bundles are half price, so you can take your Swift knowledge further without spending big! Get the Swift Power Pack to build your iOS career faster, get the Swift Platform Pack to builds apps for macOS, watchOS, and beyond, or get the Swift Plus Pack to learn advanced design patterns, testing skills, and more.

Save 50% on all our books and bundles!

Sponsor Hacking with Swift and reach the world's largest Swift community!

Archived topic

This topic has been closed due to inactivity, so you can't reply. Please create a new topic if you need to.

All interactions here are governed by our code of conduct.

Unknown user

You are not logged in

Log in or create account

Link copied to your pasteboard.