UPGRADE YOUR SKILLS: Learn advanced Swift and SwiftUI on Hacking with Swift+! >>

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": "https://firebasestorage.googleapis.com/v0/b/lightkitpresetsapp.appspot.com/o/Presets%2FWinter%2Fwinter-cover.png?alt=media&token=1ba8c8ae-ce7b-41fd-beca-0dc8dd7334cd",
      "isPremium": false,
      "isNewKit": true,
      "kitItems": [
        {
          "number": 0,
          "beforeImageURL": "https://firebasestorage.googleapis.com/v0/b/lightkitpresetsapp.appspot.com/o/Presets%2FWinter%2Fwinter-1%2Fwinter-1-before.jpg?alt=media&token=391665de-d6c3-4d52-a344-fa6197836e11",
          "afterImageURL": "https://firebasestorage.googleapis.com/v0/b/lightkitpresetsapp.appspot.com/o/Presets%2FWinter%2Fwinter-1%2Fwinter-1-after.jpg?alt=media&token=16c28047-2490-4dee-9311-8d4bf2eb36f1",
          "dngURL": "https://firebasestorage.googleapis.com/v0/b/lightkitpresetsapp.appspot.com/o/Presets%2FWinter%2Fwinter-1%2Fwinter-1-preset-file.dng?alt=media&token=eb3642f3-c774-420d-9a2f-86388dbb3bf9"
        }
      ]
    }
  ]

Structs:

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
}

ViewModel:

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

    func fetch() {

        guard let url = URL(string: "https://presetsapp.zapps.tech/presets-test.json") else {
            return
        }

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

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

        task.resume()
    }

}

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

3      

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.

4      

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

3      

TAKE YOUR SKILLS TO THE NEXT LEVEL If you like Hacking with Swift, you'll love Hacking with Swift+ – it's my premium service where you can learn advanced Swift and SwiftUI, functional programming, algorithms, and more. Plus it comes with stacks of benefits, including monthly live streams, downloadable projects, a 20% discount on all books, and free gifts!

Find out more

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.