1

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!

2
  • print("Error") => print("Error: \(error)") that might be the first step you are missing. Commented Apr 14, 2021 at 7:36
  • See this question and answer. This goes into great detail about how to fetch and convert JSON into data you can use. Commented Apr 14, 2021 at 13:52

1 Answer 1

0

You have correctly created a struct Feed but you are not using it. Call decode on it instead of [Post],

let decodedData = try JSONDecoder().decode(Feed.self, from: postData)

Also never print a hard coded string when handling errors so replace print("Error") with print(error)

Your code then becomes

do {
    if let postData = data {
        let decodedData = try JSONDecoder().decode(Feed.self, from: postData)
        DispatchQueue.main.async {
            self.post = decodedData.posts
        }
    } else {
         print("No data")
    }
} catch {
    print(error)
}
Sign up to request clarification or add additional context in comments.

1 Comment

@Safade, any feedback on this?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.