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

How can I decode a json to populate a List?

Forums > SwiftUI

I have a json string and need to decode it to populate a List. So far, so good, but I am facing a problem with the Initialization of my view:

Cannot convert value of type 'ChannelsData.Type' to expected argument type 'ChannelsData' the error happens at the line:

UserAuthResult(channels: ChannelsData)

I just can't find a solution to this problem. I thank you folks for any help.

At this time, the code I have is this:

import SwiftUI
import UIKit

struct UserAuthResult: View {
    @State var channels: ChannelsData

    var body: some View {
        VStack {
            List {
                ForEach(0 ..< channels.records.count, id: \.self) { value in

                    Section("Channel") {
                        HStack {
                            Text("\(channels.records[value].number)")
                            Spacer()
                            Text("\(channels.records[value].name)")
                        }
                        .padding()
                    }
                }
            }
        }
        .onAppear() {
            if let jsonData = channelsList.data(using: .utf8) {

                do {
                    channels = try JSONDecoder().decode(ChannelsData.self, from: jsonData)
                    print ("status = \(channels.status)")
                    print ("channels = \(channels.records.count)")

                } catch {
                    print("Error decoding JSON: \(error)")
                }
            }
        }
    }
}

struct UserAuthResult_Previews: PreviewProvider {
    static var previews: some View {
        UserAuthResult(channels: ChannelsData)
    }
}

The ChannelsData Struct is:

struct ChannelsData: Codable {
    struct Data: Codable {
        let hash: String
        let genres: [String]
    }

    struct Record: Codable {
        struct Genre: Codable {
            let id: Int
            let classification: String
            let name: String
            let startNumber: Int
            let type: String
        }

        let iconID: String?
        let number: String
        let id: Int
        let hasCatchUp: Bool
        let hasStartOver: Bool
        let genre: Genre
        let epgHash: String?
        let name: String

        private enum CodingKeys: String, CodingKey {
            case iconID = "iconId"
            case number
            case id
            case hasCatchUp
            case hasStartOver
            case genre
            case epgHash
            case name
        }
    }

    let status: String
    let code: Int
    let message: String
    let data: Data
    let records: [Record]
}

and the json (some of it) is:

let channelsList = """
{
    "status":"success",
    "code":0,
    "message":"",
    "data":{
        "hash":"dbffbf6b9c4358e13AD54FB6d1fe1e594b8810605907ac",
        "genres":[
            "FREE_TO_AIR",
            "SPORTS",
            "NEWS",
            "DOCUMENTARY",
            "KIDS",
            "MUSIC",
            "VARIETY",
            "SERIES",
            "MOVIES",
            "ADULT",
            "RADIO"
        ]
    },
    "records":[
        {
            "iconId":"436ab133df8b443BA341f2c05cd538b7acef11",
            "number":"000",
            "id":5727,
            "hasCatchUp":false,
            "hasStartOver":false,
            "genre":{
                "id":1,
                "classification":"FREE",
                "name":"FREE_TO_AIR",
                "startNumber":0,
                "type":"TV"
            },
            "epgHash":null,
            "name":"Canal do Assinante"
        },
        {

1      

Your UserAuthResult view has an instance of ChannelsData.

@State var channels: ChannelsData

In the preview you are passing the ChannelsData type to UserAuthResult instead of an instance of ChannelsData.

UserAuthResult(channels: ChannelsData)

You have two options to fix the error. The first option is to comment out the preview struct. That will remove the build error, but you will not be able to preview in Xcode.

The second option is to provide an instance of ChannelsData in the preview, such as the following code:

UserAuthResult(channels: ChannelsData())

By adding the parentheses, you are creating an instance of ChannelsData.

You may have to supply some arguments in the call to ChannelsData().

   

The error you're encountering arises because you're trying to pass the type ChannelsData instead of an instance of it. Instead of UserAuthResult(channels: ChannelsData), you need to initialize UserAuthResult with an instance of ChannelsData. Assuming channelsList is your JSON string, you should decode it first and then pass the decoded data to UserAuthResult.

For instance:

let decodedChannelsData = try JSONDecoder().decode(ChannelsData.self, from: jsonData) UserAuthResult(channels: decodedChannelsData)

   

Thanks for your answer.

I changed the code from:

UserAuthResult(channels: ChannelsData)

to:

UserAuthResult(channels: ChannelsData.init(status: "", code: 0, message: "", data: ChannelsData.Data.init(hash: "", genres: [""]), records: []))

This removed the error in the code but, when canvas try to preview the view it crashes with an error:

== PREVIEW UPDATE ERROR:

    SchemeBuildError: Failed to build the scheme “Oleiptv2”

    missing argument for parameter 'channels' in call

   

Ok, changed the code to have as much parameters as needed. First it didn't work saying that some parameter was stil missing, but after I restarted xcode, it worked fine

Thanks to all for the help.

The actual init code is:


struct UserAuthResult_Previews: PreviewProvider {
    static var previews: some View {
        UserAuthResult(
            channels: ChannelsData.init(
                status: "", 
                code: 0,
                message: "",
                data: ChannelsData.Data.init(
                    hash: "",
                    genres: [""]),
                records: [ChannelsData.Record.init(
                    iconID: "",
                    number: "",
                    id: 0,
                    hasCatchUp: false,
                    hasStartOver: false,
                    genre: ChannelsData.Record.Genre.init(
                        id: 0,
                        classification: "",
                        name: "",
                        startNumber: 0,
                        type: ""),
                        epgHash: "",
                        name: "")
                ]
            )
        )
    }
}

   

Hacking with Swift is sponsored by RevenueCat.

SPONSORED Take the pain out of configuring and testing your paywalls. RevenueCat's Paywalls allow you to remotely configure your entire paywall view without any code changes or app updates.

Click to save your free spot now

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

Reply to this topic…

You need to create an account or log in to reply.

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.