繁体   English   中英

SWIFTUI 在 ContentView 中显示 JSON 数据

[英]SWIFTUI Displaying JSON Data in ContentView

在我的内容视图中显示我的 JSON 时遇到问题。 我可以解码数据并将其保存到我打印和查看的字典中。 但是,当它使用 ForEach 在 ContentView 中显示它时。 我收到此错误无法将类型“[String: String]”的值转换为预期的参数类型“Binding”下面是我的 ContentView、Struct 和 ApiCall 的代码。 我已经阅读了有关 stackoverflow 的其他解决方案并尝试了它们,但它们不起作用。

struct ContentView: View { 

    @StateObject var api = APICALL()
    
    var body: some View {
        let country = api.storedData.countries
        
        VStack(alignment: .leading) {
            ForEach(country.id, id: \.self) { country in
                HStack(alignment: .top) {
                    Text("\(country.countries)")
                }
                
            }
            .onAppear {
                api.loadData()
            }
        }
    }
}

我的 ApiCall class 加载数据以及结构。

// MARK: - Country
struct Country: Codable, Identifiable {
    let id = UUID()
    var countries: [String: String]

    enum CodingKeys: String, CodingKey {
        case countries = "countries"
    }
}

class APICALL: ObservableObject {
    
    @Published var storedData = Country(countries: [:])
    
    func loadData() {
        let apikey = ""
        
        guard let url = URL(string:"https://countries-cities.p.rapidapi.com/location/country/list?rapidapi-key=\(apikey)") else {
            print("Your Api end point is Invalid")
            return
        }
        let request = URLRequest(url: url)
        URLSession.shared.dataTask(with: request) { data, response, error in
            if let data = data {
                if let response = try? JSONDecoder().decode(Country.self, from: data) {
                    DispatchQueue.main.async {
                        self.storedData.countries = response.countries
                        print(self.storedData.countries)
                    }
                    return
                }
            }
        }
        .resume()
    }
}

任何朝着正确方向的点都是绝对有帮助的。

您可以尝试这种方法来显示您的国家数据:

struct ContentView: View {
    @StateObject var api = APICALL()
    
    var body: some View {
        VStack(alignment: .leading) {
            // -- here --
            ForEach(Array(api.storedData.countries.enumerated()), id: \.0) { index, country in 
                HStack(alignment: .top) {
                    Text("\(country.key)   \(country.value)")
                }
            }
            .onAppear {
                api.loadData()
            }
        }
    }
}

如果您愿意,也可以使用它:

    ForEach(api.storedData.countries.sorted(by: >), id: \.key) { key, value in
        HStack(alignment: .top) {
            Text("\(key)   \(value)")
        }
    }

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM