0

Error:

keyNotFound(CodingKeys(stringValue: "topic", intValue: nil), Swift.DecodingError.Context(codingPath: [], debugDescription: "No value associated with key CodingKeys(stringValue: "topic", intValue: nil) ("topic").", underlyingError: nil))

My code:

class ViewController: UIViewController {

    @IBOutlet weak var prizeLabel: UILabel!
    @IBOutlet weak var priceLabel: UILabel!
    @IBOutlet weak var timeLabel: UILabel!
    @IBOutlet weak var categoryLabel: UILabel!
    @IBOutlet weak var contentLabel: UILabel!
    @IBOutlet weak var titleLabel: UILabel!
    override func viewDidLoad() {

        
        super.viewDidLoad()
        

           // 1
           let urlString = "http:..{local-host-address}.../post"
           guard let url = URL(string: urlString) else { return }
           
           // 2
           URLSession.shared.dataTask(with: url) { (data, response, error) in
               if error != nil {
                   print(error!)
               }

               guard let data = data else { return }
               do {
                   // 3
                   //Decode data
                   let JSONData = try JSONDecoder().decode(JSONTest.self, from: data)

                   // 4
                   //Get back to the main queue
                   DispatchQueue.main.async {
                      
                       self.timeLabel.text = JSONData.time
                       self.priceLabel.text = JSONData.price
                       self.prizeLabel.text = JSONData.prize
                       self.contentLabel.text = JSONData.content
                       self.categoryLabel.text = JSONData.category
                       self.titleLabel.text = JSONData.topic
                       
                   }

               } catch let jsonError {
                   print(jsonError)
               }
               // 5
               }.resume()
       }
        
    }


    struct JSONTest: Codable {
        var topic: String
        var content: String
        var category: String
        var time: String
        var price: String
        var prize: String
        
        init(topic: String, content: String, category: String, time: String, price: String, prize: String) {
               self.topic = topic
               self.content = content
               self.category = category
               self.time = time
               self.price = price
               self.prize = prize
           }
    }

BTW: I also have another similar code with different error but first I would like to solve this one

Thanks!

marc_s
  • 732,580
  • 175
  • 1,330
  • 1,459
D-wash
  • 1
  • 1
  • 3
  • Does this answer your question? [Swift 4 Decodable - No value associated with key CodingKeys](https://stackoverflow.com/questions/55562253/swift-4-decodable-no-value-associated-with-key-codingkeys) – koen Feb 25 '22 at 16:38
  • This tells you server not share topic with you, please add optional to topic, and check if your problem has fixed like this: var topic: String? and share your result – Reza Khonsari Feb 25 '22 at 16:40
  • if your problem no solved, you should edit your question and share your server json – Reza Khonsari Feb 25 '22 at 16:43
  • Without knowing the json, it’s very hard to tell. Add `if let s = String(data: data) { print(s) }` to print the json returned and add the output to the question – Joakim Danielson Feb 25 '22 at 16:56
  • @RezaKhonsari can you please demonstrate with a code – D-wash Feb 25 '22 at 16:57
  • ``` {"scrims":[{"topic":"tv","content":"done","catagory":"gg","price":"Rs.100","prize":"Rs.1000","id":495818}]} ``` **THE JSON DATA** @JoakimDanielson – D-wash Feb 25 '22 at 16:57
  • Add that to the question for clarity but you must always decode from the top level so add a struct with property scrims that is an array of JSONTest and use this new struct in your decode call – Joakim Danielson Feb 25 '22 at 16:59
  • @JoakimDanielson it says "Value of type 'scrims' has no member 'time'" – D-wash Feb 25 '22 at 17:18
  • this thing got me stuck for 2 days now.. imma cry soon – D-wash Feb 25 '22 at 17:48
  • Then you didn't do what I said. `struct Root: Codable { let scrims: [JSONTest] }` – Joakim Danielson Feb 25 '22 at 18:35
  • @JoakimDanielson I did the exact same – D-wash Feb 26 '22 at 05:42
  • There is no key "time" in your json so you can't add an extra property like that. If you want to have extra properties in your struct then you need to add a `CodingKeys` enum that list which properties the decoder should decode. – Joakim Danielson Feb 26 '22 at 08:19
  • oke, ill try that. – D-wash Feb 26 '22 at 12:10
  • @JoakimDanielson bro, still things are the same.. :( – D-wash Feb 26 '22 at 12:29
  • ``` struct JSONTest: Codable { let topic: String let content: String let catagory: String let time: String let price: String let prize: String enum CodingKeys: String, CodingKey { case topic = "topic" case content = "content" case catagory = "catagory" case time = "time" case price = "price" case prize = "prize" } ``` isn't it correct? – D-wash Feb 26 '22 at 12:30
  • No, you can only include keys in the enum that exists in your json as I wrote. So remove `time` from the CodingKeys enum – Joakim Danielson Feb 26 '22 at 13:18
  • nah bro... you got insta or anything? imma send some pics bro... this thing killing my brain.. – D-wash Feb 26 '22 at 13:34
  • @JoakimDanielson dude!!! it's telling the same for other things too – D-wash Feb 26 '22 at 13:39
  • You need to troubleshoot this yourself, I can’t babysit you through all of this. If you don’t learn anything from the help you get then what is the point – Joakim Danielson Feb 26 '22 at 13:43
  • yeah.. but, just shifted to iOS dev so I've got a lil less idea abt what's going on. I really need some good help on this rn.. – D-wash Feb 26 '22 at 13:54

1 Answers1

0

THIS QUESTION WAS FIXED AFTER I DID SOME CHANGES:

FINAL CODE:

override func viewDidLoad() {
        super.viewDidLoad()
        
        if let url = URL(string: "http://{local-host}/post") {
           URLSession.shared.dataTask(with: url) { data, response, error in
        if let data = data {
            let jsonDecoder = JSONDecoder()
            do {
            let parsedJSON = try jsonDecoder.decode(parsingss.self, from: data)
                
                print(parsedJSON)
                    }
            catch {
            print(error)
                        
                    }
                   }
               }.resume()
            }
    }
    struct everything: Codable{
        let topic: String
        let content: String
        let category: String
        let time: String
        let price: String
        let prize: String
    }
    struct parsingss : Codable {
        let scrims: [everything]
    }
}

The data will be shown in the terminal.

I have no idea how to display it on a label btw..

marc_s
  • 732,580
  • 175
  • 1,330
  • 1,459
D-wash
  • 1
  • 1
  • 3