IOS swiftUI can't read json from local files [closed]

淺唱寂寞╮ 提交于 2021-02-11 17:51:07

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!