TEAM LICENSES: Save money and learn new skills through a Hacking with Swift+ team license >>

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.


Hacking with Swift is sponsored by String Catalog.

SPONSORED Get accurate app localizations in minutes using AI. Choose your languages & receive translations for 40+ markets!

Localize My App

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.