问题
I'm new with IOS development, I'm using swiftUI and following this tutorial https://developer.apple.com/tutorials/swiftui/building-lists-and-navigation but I have been stuck here for a while, In the tutorial, they pass one item from a json file in the project
struct LandmarkRow_Previews: PreviewProvider {
static var previews: some View {
LandmarkRow(landmark: landmarkData[0])
}
}
I'm trying to do the same with my own data, I have a file called sorteosData.json but when I try to pass the first item to the preview it says "use of unresolved identifier"
struct PastSorteoRowView_Previews: PreviewProvider {
static var previews: some View {
PastSorteoRowView(sorteo: sorteosData[0])
}
Xcode doesn't recognize sorteosData[0], how can I solve this? I have a followed all the steps from the tutorial, but for some reason, I can't pass my data to the preview
回答1:
With JSON
you need use JSONDecoder()
. Assume that we have this file:
[
{
"name": "Banana",
"points": 200,
"description": "A banana grown in Ecuador."
},
{
"name": "Orange",
"points": 100
}
]
For convenience you can create a struct
(convenient even for nested elements):
struct product: Codable, Hashable {
var name: String
var points: Int
var description: String?
}
Create a function to parse your JSON
in bundle called list.json
that return an array
of struct product
:
func jsonTwo() -> [product]{
let url = Bundle.main.url(forResource: "list", withExtension: "json")!
let data = try! Data(contentsOf: url)
let decoder = JSONDecoder()
let products = try? decoder.decode([product].self, from: data)
return products!
}
Finally set your interface:
var body: some View {
List{
ForEach(jsonTwo(), id: \.self) { item in
VStack(alignment: .leading, spacing: 0){
Text("name:\(item.name) - points:\(item.points)")
Text("\(item.description ?? "")")
}
}
}
}
Complete code:
struct product: Codable, Hashable {
var name: String
var points: Int
var description: String?
}
struct ContentView: View {
func jsonTwo() -> [product]{
let url = Bundle.main.url(forResource: "list", withExtension: "json")!
let data = try! Data(contentsOf: url)
let decoder = JSONDecoder()
let products = try? decoder.decode([product].self, from: data)
return products!
}
var body: some View {
List{
ForEach(jsonTwo(), id: \.self) { item in
VStack(alignment: .leading, spacing: 0){
Text("name:\(item.name) - points:\(item.points)")
Text("\(item.description ?? "")")
}
}
}
}
}
struct ContentView_Previews: PreviewProvider {
static var previews: some View {
ContentView()
}
}
来源:https://stackoverflow.com/questions/61482166/ios-swiftui-cant-read-json-from-local-files