Reputation: 29
I recently started learning to code in Swift and I have been struggling to fetch data from an API. This is what the data looks like:
{
"status":200,
"posts":[
{
"text":"djnkdnwnjdewkn",
"date":"08/07/2012"
},
{
"text":"dskndkc ksdskj n",
"date":"08/17/2012"
},
{
"text":"dkjdjincidjn",
"date":"09/07/2012"
}
]
}
And here is the code I have used:
import SwiftUI
import Foundation
import Combine
struct Post: Codable, Identifiable {
public var id = UUID()
public var text, date: String
}
struct Feed: Codable {
public var status: Int
public var posts: [Post]
}
class FetchPosts: ObservableObject {
@Published var posts = [Post]()
init() {
let url = URL(string: "api goes here")!
URLSession.shared.dataTask(with: url) {(data, response, error) in
do {
if let postData = data {
let decodedData = try JSONDecoder().decode(Feed.self, from: postData)
DispatchQueue.main.async {
self.posts = decodedData.posts
}
} else {
print("No data")
}
} catch {
print(error)
}
}.resume()
}
}
struct FeedView: View {
@ObservedObject var fetch = FetchPosts()
var body: some View {
ScrollView{
VStack {
ForEach(fetch.posts) { post in
VStack(alignment: .leading) {
Text(post.text)
Text("\(post.date)")
.font(.system(size: 11))
.foregroundColor(Color.gray)
}
}
}
}
}
}
I haven't been able to generate any output so far but I have been getting an error:
"keyNotFound(CodingKeys(stringValue: "id", intValue: nil), Swift.DecodingError.Context(codingPath: [CodingKeys(stringValue: "posts", intValue: nil), _JSONKey(stringValue: "Index 0", intValue: 0)], debugDescription: "No value associated with key CodingKeys(stringValue: "id", intValue: nil) ("id").", underlyingError: nil))"
Any help would be greatly appreciated!
Upvotes: 1
Views: 120
Reputation: 51821
If not all properties of your struct are part of the json you need to define a CodingKey enum to the struct and list the properties that is included in the json
enum CodingKeys: String, CodingKey {
case text, data
}
Upvotes: 1
Reputation: 100503
Add CodingKeys
struct Post: Codable, Identifiable {
public var id = UUID()
public var text, date: String
enum CodingKeys: String, CodingKey { // add this for keys to be decoded
case text, date
}
}
Upvotes: 1