-2

Error Message: Fatal Error in ExtensionFile.swift

Trying to retrieve info from the json file but getting a fatal error. JSON link -> https://site.api.espn.com/apis/site/v2/sports/basketball/wnba/news

I only want the headline and image with caption to display. Thank you in advance for your help.

Could you provide code that will display the images as well?

struct HomeView: View {

  //MARK: - PROPERTIES
  let articles: Articles = Bundle.main.decode("wnba.json")


  //MARK: - BODY

    var body: some View {
      Text(articles.description)
      Text(articles.headline)
    //Display Images?
      }
    }

Here is the ExtensionFile.swift that is causing errors

 extension Bundle {
    func decode<T: Codable>(_ file: String) -> T {
    let decoder = JSONDecoder()

    //locate JSON file
    guard let url = self.url(forResource: file, withExtension: nil) else {
      fatalError("Failed to locate \(file) in bundle")
    }

    do {
      let data = try Data(contentsOf: url)
      return try decoder.decode([Articles].self, from: data) as! T

    } catch {
        fatalError("Failed to decode \(file) from bundle.")
    }
  }
}
} Structures:

struct Articles: Codable { 
let description: String 
let headline: String 
let images: [Images]
}

struct Images: Codable, Identifiable { 
let name: String? 
let width: Int? 
let caption : String? 
let id: Int? 
let url: String? 
let height: Int? 
}
3
  • Instead of a fatalerror try print(error) you will get a much better description for debugging. Commented Jun 21 at 15:34
  • Common mistake. You ignore the root object, the dictionary with the articles key. Closely related: stackoverflow.com/questions/59074719/how-do-i-map-api/…
    – vadian
    Commented Jun 21 at 15:36
  • thank you @vadian this was extremely helpful.
    – snesdev
    Commented Jun 22 at 2:30

0

Browse other questions tagged or ask your own question.