Thank you guys.I am trying to do this for a long time and after trying this other tutorial I changed my code to this one: It returns an error after falling on the catch of the parse function.
struct ContentView: View {
var body: some View {
VStack {
Image(systemName: "globe")
.imageScale(.large)
.foregroundColor(.accentColor)
Text("Hello, world!")
}
.padding().onAppear {
if let localData = self.readLocalFile(forName: "vinyls") {
self.parse(jsonData: localData)
}
}
}
private func readLocalFile(forName name: String) -> Data? {
do {
if let bundlePath = Bundle.main.path(forResource: name, ofType: "json"),let JSONData = try String(contentsOfFile: bundlePath).data(using: .utf8) {
return JSONData
}
} catch {
print("ERROR readLocalFile")
}
return nil
}
private func parse(jsonData: Data) {
do {
let decodedData = try JSONDecoder().decode(VinylModel.self, from: jsonData)
print("Title : ", decodedData.title)
print("Artist : ",decodedData.artist)
} catch {
print("ERROR Parse")
}
}
private func loadJSON(fromURLString urlString: String,completion: @escaping (Result<Data,Error>) -> Void) {
if let url = URL(string: urlString) {
let urlSession = URLSession(configuration: .default).dataTask(with: url) { (data, response, error) in
if let error = error {
completion(.failure(error))
}
if let data = data {
completion(.success(data))
}
}
urlSession.resume()
}
}
}
the model file:
struct VinylModel: Codable {
let id: Int
let title: String
let artist: String
let isOut: String
let label: String
let vinylAudoID: String
let vinylCountry: String
let vinylFormat: String
let vinylID: String
let vinylLocation: String
let year: String
}
the json file:
[
{
"id" : 1,
"title" : "I’m Missing You",
"artist" : "Fabrica",
"isOut" : "False",
"label" : "Dance Pool",
"vinylAudoID" : "00mwDSOTStNtIMRWIZPs",
"vinylCountry" : "Italy",
"vinylFormat" : "12",
"vinylID" : "DAN6652126",
"vinylLocation" : "LR25",
"year" : "1997"
},
{
"id" : 2,
"title" : "No More, Baby",
"artist" : "Disco Blu",
"isOut" : "False",
"label" : "DJ Approved",
"vinylAudoID" : "02Q6i5tJfUBNEXxanfMM",
"vinylCountry" : "Italy",
"vinylFormat" : "12",
"vinylID" : "APP 9706",
"vinylLocation" : "LR11",
"year" : "1997"
},
{
"id" : 3,
"title" : "Carramba",
"artist" : "Arena Blanca",
"isOut" : "False",
"label" : "Outta Records",
"vinylAudoID" : "02loclZIMqGHzIXI9Xo5",
"vinylCountry" : "Italy",
"vinylFormat" : "12",
"vinylID" : "OTA696004",
"vinylLocation" : "LR19",
"year" : "1996"
}
]
thank u