【问题标题】:Swift shows an error on a view with API fetchSwift 在使用 API 获取的视图上显示错误
【发布时间】:2023-02-25 01:17:48
【问题描述】:

我是 Swift 的新手,正在尝试编写一个视图来显示从 API 获取的数据。不幸的是,它会在预览时抛出错误,并显示一条我不理解的奇怪消息。

我正在按照本教程创建 UI:

SwiftUI Tutorial

这是我的代码:

import SwiftUI

struct LowestPriceView: View {
    @State var results = [LowestPriceEntry]()
    
    var body: some View {
        VStack {
            ForEach(results, id: \.id) { item in
                LowestPriceRow(item: item)
            }.onAppear(perform: loadLowestPriceData)
        }
    }
    
    func loadLowestPriceData() {
        guard let url = URL(string: "http://\(Config.APIBaseUrl)/api/lowest/") else {
            print("Lowest price API endpoint 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([LowestPriceEntry].self, from: data) {
                    DispatchQueue.main.async {
                        self.results = response
                    }
                    return
                }
            }
        }.resume()
    }
}

struct LowestPriceRow: View {
    let item: LowestPriceEntry
    
    var body: some View {
        VStack(alignment: .leading) {
            HStack {
                Text(String(format: "%.2f  ", item.price))
                    .foregroundColor(Color("AccentColor")).bold() +
                Text(item.fuel_type)
                Spacer()
                ForEach(item.providers.reversed(), id: \.self) { provider in
                    HStack {
                        Image("\(provider.lowercased())_logo")
                            .resizable()
                            .frame(width: 27, height: 27)
                            .padding(.leading, 5)
                    }
                }
            }
        }
    }
}

struct LowestPriceView_Previews: PreviewProvider {
    static var previews: some View {
        LowestPriceView()
            .previewLayout(.sizeThatFits)
    }
}

错误信息:

RemoteHumanReadableError: Unable to take preview snapshot

No image for snapshot of scene: <FBScene: 0x600003e9cb40; FBSceneManager:SimDisplayScene-133-static>

==================================

|  MessageSendFailure: Message send failure for <ServiceMessage 1774: update>

我试图用谷歌搜索它,但没有发现任何有意义的东西。

【问题讨论】:

  • 图片资源(...._logo)是否都在Assets目录下?
  • 是的,这不是问题

标签: swiftui


【解决方案1】:

我通过将 .onAppear(perform: loadLowestPriceData) 移到 VStack 上来修复它

var body: some View {
    VStack {
        ForEach(results, id: .id) { item in
             LowestPriceRow(item: item)
        }
    }.onAppear(perform: loadLowestPriceData)
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-11-02
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多