在SwiftUI中从JSON获取数据

ttygqcqt  于 11个月前  发布在  Swift
关注(0)|答案(1)|浏览(146)

我正在尝试使用GitHub存储库中的.json文件。(Here
我创建了一个函数,它应该从我的项目中的.json文件中获取数据。

private func fetchData() {
    if let url = Bundle.main.url(forResource: "funko_pop", withExtension: "json") {
        let task = URLSession.shared.dataTask(with: url) { data, response, error in
            if let error = error {
                print("Errore nella richiesta: \(error)")
                return
            }
            
            guard let data = data else {
                print("Dati mancanti.")
                return
            }
            
            do {
                let decoder = JSONDecoder()
                let decodedData = try decoder.decode([FunkoPop].self, from: data)
                
                DispatchQueue.main.async {
                    funkoPops = decodedData
                }
            } catch {
                print("Errore nella decodifica JSON: \(error)")
            }
        }
        
        task.resume()
    } else {
        print("URL non valido.")
    }
}

字符串
下面是我的struct:

struct FunkoPop: Codable {
    let handle: String
    let imageName: String
    let title: String
    let series: [String]
}

ryevplcw

ryevplcw1#

假设你声明了一个有效的@State var funkoPops: [FunkoPop],尝试下面的示例代码,从你的项目中读取你的文件:

private func fetchData() {
     guard let url = Bundle.main.url(forResource: "funko_pop", withExtension: ".json") else {
         print("---> url error")
         return
     }
     do {
         let jsonData = try Data(contentsOf: url)
         let decodedData = try JSONDecoder().decode([FunkoPop].self, from: jsonData)
       // print(decodedData.count)
         funkoPops = decodedData
     } catch {
         print("---> decoding error: \(error)")
     }
 }

字符串
编辑1:
这里是我的完整测试代码,直接从github或项目中的文件获取和解码JSON数据。对我来说效果很好,在ios17设备,MacCatalyst和MacOS上测试过。

import Foundation
 import SwiftUI

struct FunkoPop: Codable, Identifiable {
    let id = UUID()
    var handle: String
    var imageName: String
    var title: String
    var series: [String]
    
    enum CodingKeys: String, CodingKey {
        case handle, imageName, title, series
    }
}

struct ContentView: View {
    @State var funkoPops = [FunkoPop]()
    
    var body: some View {
        Text("\(funkoPops.count)")
        List(funkoPops){ item in
            Text(item.title)
        }
        .task {
            await fetchDataGithub()  // <--- from github repo
        }
//            .onAppear {
//                fetchDataFile()  // <--- from local file
//            }
    }
    
    func fetchDataGithub() async {
        guard let url = URL(string: "https://raw.githubusercontent.com/kennymkchan/funko-pop-data/master/funko_pop.json") else {
            print("---> url error")
            return
        }
        do {
            let (data, _) = try await URLSession.shared.data(from: url)
            let decodedData = try JSONDecoder().decode([FunkoPop].self, from: data)
            print(decodedData.count)
            funkoPops = decodedData
        } catch {
            print("---> decoding error: \(error)")
        }
    }
    
    private func fetchDataFile() {
        guard let url = Bundle.main.url(forResource: "funko_pop", withExtension: ".json") else {
            print("---> url error")
            return
        }
        do {
            let jsonData = try Data(contentsOf: url)
            let decodedData = try JSONDecoder().decode([FunkoPop].self, from: jsonData)
            print(decodedData.count)
            funkoPops = decodedData
        } catch {
            print("---> decoding error: \(error)")
        }
    }
    
}

相关问题