IOS swiftUI 无法从本地文件读取 json [英] IOS swiftUI can't read json from local files

查看:26
本文介绍了IOS swiftUI 无法从本地文件读取 json的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是 IOS 开发新手,我正在使用 swiftUI 并遵循本教程

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

解决方案

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()
    }
}

这篇关于IOS swiftUI 无法从本地文件读取 json的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆