'I got this error in swift storyboard keyNotFound(CodingKeys(stringValue: "topic", intValue: nil), Swift.DecodingError
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!
Solution 1:[1]
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..
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | marc_s |
