I recently started using 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 {
public var text, date: String
}
struct Feed: Codable {
public var status: Int
public var posts: [Post]
}
class FetchPosts: ObservableObject {
@Published var post = [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([Post].self, from: postData)
DispatchQueue.main.async {
self.post = decodedData
}
} 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: 13))
}
}
}
}
}
}
I haven't been able to generate any output so far. I'm not sure if the problem is with the way I created the structs or if I'm just not using the JSONDecoder correctly. Any pointers would be greatly appreciated!
print("Error")=>print("Error: \(error)")that might be the first step you are missing.