2021年1月2日星期六

Updating List from JSON data SwiftUI

I'm having a hard time understanding how JSON data is supposed to be updated in a List in SwiftUI. I'm fetching data from NewsAPI.org, my list and detail views work just fine. I'm trying to figure out how to keep the list up-to-date when my json data changes, but the data remains outdated. I'm still a beginner to swift so if I made a mistake any help would be greatly appreciated.

UPDATED I added a relative time function, it indeed does not update either.

My data class

struct News : Codable {      var articles : [Article]  }    struct Article : Codable {      let description : String?      let title : String?      let author: String?      let source: Source      let content: String?      let publishedAt: String?  }    struct Source: Codable {      let name: String?  }    class NewsData: ObservableObject {     @Published var news: News = News(articles: [])            init() {          load()      }            func load() {          guard let url = URL(string: "http://newsapi.org/v2/top-headlines?country=us&apiKey=API_KEY_HERE") else { return }          let request = URLRequest(url: url)          URLSession.shared.dataTask(with: request) { data, response, error in              if let data = data {                  if let response = try? JSONDecoder().decode(News.self, from: data) {                      DispatchQueue.main.async() {                          self.news = response                      }                  }              }          }          .resume()      }  }  

My ContentView

func relativeDate(date: String) -> String {      let formatter = RelativeDateTimeFormatter()      let dateFormatter = ISO8601DateFormatter()      return formatter.localizedString(for: dateFormatter.date(from: date) ?? Date(), relativeTo: Date())  }      struct ContentView: View {      @ObservedObject var news: NewsData            var body: some View {          NavigationView {              List(news.news.articles , id: \.title) { article in                  VStack (alignment: .leading, spacing: 5){                      Text(article.title ?? "")                          .fontWeight(.bold)                          .font(.subheadline)                          .lineLimit(1)                      Text(article.description ?? "")                          .font(.subheadline)                          .foregroundColor(.secondary)                          .lineLimit(1)                     Text(relativeDate(date: article.publishedAt ?? ""))                           .font(.subheadline)                           .foregroundColor(.secondary)                  }              }              .navigationTitle("News")          }      }  }  
https://stackoverflow.com/questions/65543473/updating-list-from-json-data-swiftui January 03, 2021 at 03:57AM

没有评论:

发表评论