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

SOLVED: Error Decoding

Forums > SwiftUI

struct Produtos : Identifiable, Codable{
    var id = UUID()
    var produto : String
    var descricao : String
    var imagem : String
    var preco : Double
    var destaque : Bool
    var categoria : String
    var ordenacao : Int
}
extension Bundle {
    func decode<T: Decodable>(_ type: T.Type, from file: String) -> T {
        guard let url = self.url(forResource: file, withExtension: nil) else {
            fatalError("Failed to locate \(file) in bundle.")
        }

        guard let data = try? Data(contentsOf: url) else {
            fatalError("Failed to load \(file) from bundle.")
        }

        let decoder = JSONDecoder()

        guard let loaded = try? decoder.decode(T.self, from: data) else {
            fatalError("Failed to decode \(file) from bundle.")
        }

        return loaded
    }
}
func buscaJSON_local() {
        self.listagemProdutos = Bundle.main.decode([Produtos].self, from: "arquivo.json")
    }

JSON FILE

[{
        "produto": "a",
        "descricao": "Qualquer descricao aqui.",
        "imagem": "foto",
        "preco": 12.32,
        "destaque": true,
        "categoria": "teste",
        "ordenacao": 1
    },....

ErrorlojaModelo/Decoder.swift:24: Fatal error: Failed to decode arquivo.json from bundle. 2021-06-14 19:07:09.972785-0300 lojaModelo[7473:363267] lojaModelo/Decoder.swift:24: Fatal error: Failed to decode arquivo.json from bundle. (lldb)

Whats my error? UIID??? Sintax??? JSON FILE??

PLEASE help me..

3      

The error message is from this part of your code

guard let loaded = try? decoder.decode(T.self, from: data) else {
    fatalError("Failed to decode \(file) from bundle.")
}

The try? failed, so indicates a failure in the JSON.

This suggests to check the file arquivo.json.

3      

Don't use try? when decoding JSON because, as you discovered, it swallows any errors that may occur by turning them into an Optional. You should only use the try? method when all you care about is the fact of failure but not the reason.

Instead, use a do {}... catch {} block and check error (not localizedError) to see exactly what went wrong.

In this case, it's because of the id property. If you add:

    enum CodingKeys: String, CodingKey {
        case produto, descricao, imagem, preco, destaque, categoria, ordenacao
    }

to let Swift know you only want to decode those properties, it will work.

4      

dont work, i pickup this code of the restaurant project by hack with swift..... but ok, i will try to study to undestend better this concepts... but dont works.... =.. may another thing?

3      

What does "don't work" mean? Did you change your code as suggested so that you get a better error message? If so, what was it?

It might help if we could see an actual sample of what you are trying. Like, maybe post your arquivo.json file?

4      

Hi @gfmolon

@roosterboy is correct it is to do with the var id = UUID(). You can do either

Delete var id = UUID() and add var id: String { produto }. produto has to be unique (no dupicates)

or as @roosterboy suggests

struct Produtos : Identifiable, Decodable {
    let id = UUID()
    let produto : String
    let descricao : String
    let imagem : String
    let preco : Double
    let destaque : Bool
    let categoria : String
    let ordenacao : Int

    enum CodingKeys: CodingKey {
        case produto, descricao, imagem, preco, destaque, categoria, ordenacao
    }
}

You do not have to change the extension Bundle as this will not throw an error

4      

thank you my friends, i really aprieciate your help, this comunity is amazing... learn swiftui, ios development its beem really fun... i put the enums inside the struct and the code works correctly... !!! thank you!!!

3      

Im study only one month computer programming and ios and build things its have been really cool.

3      

Now im trynt to consume via API...

VIEWMODEL

 // BUSCA DADOS DE UMA API
    func buscaAPI() {
        // fetch json, decode, e update property array
        guard let url = URL(string: apiUrl) else { return }
        URLSession.shared.dataTask(with: url) { (data, resp, err) in
            // check error

            DispatchQueue.main.sync {
                self.listagemProdutos = try! JSONDecoder().decode([Produtos].self, from: data!)
            }

        }.resume()
    }

but my app dont crash nothing, but data dont appers.... with the same json file... i use it and works, but via API, dont push any data. What im doing wrong, the url is correct, my xcode:

2021-06-15 08:33:40.823769-0300 lojaModelo[1115:29813] [] nw_protocol_get_quic_image_block_invoke dlopen libquic failed

just it.

3      

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.

Learn more here

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.