簡體   English   中英

SwiftUI 列表未出現

[英]SwiftUI List doesn't appear

早上好,

我的 SwiftUI 列表有問題。 從我的 JSON 正確接收數據並將其作為字符串之后,信息似乎沒有出現在我的列表視圖中。

struct Lists: View{

@State private var Countries = [Country]()

var body: some View {
        List(Countries, id: \.id) { item in
            VStack(alignment: .leading) {
                Text(item.Country)
                    .font(.headline)
                Text(item.Country)
            }
        }.onAppear(perform: loadData)
    
}

func loadData() {
    guard let url = URL(string: "https://api.covid19api.com/summary") else {
        print("Invalid URL")
        return
    }
    let request = URLRequest(url: url)
    let jsonData = (try! String(contentsOf: url))
    /*print(jsonData)*/
    
    URLSession.shared.dataTask(with: request) { data, response, error in
        
        let decoder = JSONDecoder()
        decoder.dateDecodingStrategy = .iso8601
        
        if let jsonData = data {
            do {
                let decodedResponse = try decoder.decode(AllCountries.self, from: jsonData)
                print(decodedResponse.Countries)
                
            } catch let error as NSError {
            /*print("json error: \(error.localizedDescription)")*/
            print("json error: \(error)")
            
        }
    }
    }.resume()
}

這是我的 object 結構:

struct AllCountries: Decodable {
    var Countries: [Country]
}

struct AllCountries: Decodable {
    var Countries: [Country] }
    struct Country: Decodable, Identifiable {
    let id = UUID()
    var Country, CountryCode, Slug: String
    var NewConfirmed, TotalConfirmed, NewDeaths, TotalDeaths: Int
    var NewRecovered, TotalRecovered: Int
    var Date: Date
    }

    enum CodingKeys: String, CodingKey {
        case Country = "Country"
        case CountryCode = "CountryCode"
        case Slug = "Slug"
        case NewConfirmed = "NewConfirmed"
        case TotalConfirmed = "TotalConfirmed"
        case NewDeaths = "NewDeaths"
        case TotalDeaths = "TotalDeaths"
        case NewRecovered = "NewRecovered"
        case TotalRecovered = "TotalRecovered"
        case Date = "Date"       
    }
}

這是我打印時“數據”結果的開頭:

[_IOS_Project.Country(id: EB629D42-8278-444C-878E-A6EAC46BD5D6, Country: "Afghanistan", CountryCode: "AF", Slug: "afghanistan", NewConfirmed: 546, TotalConfirmed: 28424, NewDeaths: 21, TotalDeaths: 569, NewRecovered: 330, TotalRecovered: 8292, Date: 2020-06-21 19:37:01 +0000), _IOS_Project.Country(id: 8DDDCA84-CE99-4374-A487-096BFDF8A467, Country: "Albania", CountryCode: "AL", Slug: "albania", NewConfirmed: 53, TotalConfirmed: 1891, NewDeaths: 1, TotalDeaths: 43, NewRecovered: 12, TotalRecovered: 1126, Date: 2020-06-21 19:37:01 +0000),

有人可以指出我在這個問題上的正確方向嗎?

提前致謝:)

您的代碼似乎存在一些問題。

首先是變量的命名。 Swift 中的變量名以小寫字母開頭,結構和類以大寫字母開頭。

其次,您沒有將 URLRequest 的響應分配給國家 state 變量,這是主要問題。

第三,您粘貼的代碼似乎格式不正確。

我將您的代碼放入一個新項目中,並通過一些調整使其工作。

struct ContentView: View {

    @State private var countries = [AllCountries.Country]()

    var body: some View {
        List(countries, id: \.id) { item in
            VStack(alignment: .leading) {
                Text(item.country)
                    .font(.headline)
                Text(item.country)
            }
        }.onAppear(perform: loadData)

    }

    func loadData() {
        guard let url = URL(string: "https://api.covid19api.com/summary") else {
            print("Invalid URL")
            return
        }
        let request = URLRequest(url: url)

        URLSession.shared.dataTask(with: request) { data, response, error in

            let decoder = JSONDecoder()
            decoder.dateDecodingStrategy = .iso8601

            if let jsonData = data {
                do {
                    let decodedResponse = try decoder.decode(AllCountries.self, from: jsonData)
                    print(decodedResponse.countries)
                    // You should update this on the main thread
                    DispatchQueue.main.async {
                        // this assigns the values you received to the state variable countries
                        self.countries = decodedResponse.countries
                    }

                } catch let error as NSError {
                    print("json error: \(error)")
                }
            }
        }.resume()
    }
}

請注意,在loadData function 中,我將來自 URLRequest 的響應分配給countries變量。 因為這是一個@State變量,它會導致屏幕在更改時重新加載。 你沒有這樣做,所以你的 UI 不知道它需要更新。

我還更新了您的變量名稱,使它們小寫。

struct AllCountries: Decodable {
    var countries: [Country]

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

    struct Country: Decodable, Identifiable {
        let id = UUID()
        var country, countryCode, slug: String
        var newConfirmed, totalConfirmed, newDeaths, totalDeaths: Int
        var newRecovered, totalRecovered: Int
        var date: Date

        enum CodingKeys: String, CodingKey {
            case country = "Country"
            case countryCode = "CountryCode"
            case slug = "Slug"
            case newConfirmed = "NewConfirmed"
            case totalConfirmed = "TotalConfirmed"
            case newDeaths = "NewDeaths"
            case totalDeaths = "TotalDeaths"
            case newRecovered = "NewRecovered"
            case totalRecovered = "TotalRecovered"
            case date = "Date"
        }
    }
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM