3使用Contentful和SwiftUI从API调用数据时出现错误

问题描述

请原谅我,因为我是SwiftUI的新手...我试图从CMS中提取数据并将其放入我的应用程序,但是每次尝试检索和放置数据时都会抛出三个错误...

在读取“ api.beers.title”,“ api.beers.type”和“ api.beers.description”的部分中突出显示错误

错误

  • “ API”类型的值使用根类型“ API”的密钥路径没有动态成员“啤酒”
  • 引用下标'subscript(dynamicmember :)'需要包装器'Observedobject.Wrapper'
  • 初始化器'init(_ :)'要求'Binding'符合'StringProtocol'

API调用代码

@RequestMapping(value = "/json/app/{appId}/{entityDefId}/saveentity",method = RequestMethod.POST)
public ResponseEntity<String> saveEntity(@PathVariable("appId") int appId,@PathVariable("entityDefId") int entityDefId,@RequestBody String json) throws Exception {
func getArray(id: String,completion: @escaping([Entry]) -> ()) {
    let query = Query.where(contentTypeId: id)

    client.fetchArray(of: Entry.self,matching: query) { result in
        switch result {
        case .success(let array):
            dispatchQueue.main.async {
               completion(array.items)
            }
        case .failure(let error):
            print(error)
        }
    }
}

class API: ObservableObject {
    @Published var draft: [Draft] = draftData

    init() {
        getArray(id: "beers") { (items) in
            items.forEach { (item) in
                self.draft.append(Draft(
                    title: item.fields["title"] as! String,type: item.fields["type"] as! String,description: item.fields["type"] as! String
                ))
            }
        }
    }
}

解决方法

  1. 您的草稿是数组,您可以通过诸如Text(api.draft [0] .title)之类的索引进行访问
  2. @已发布的var草稿:[草稿] = draftData而不是@已发布的var草稿:[草稿] = []

已更新:

class API: ObservableObject {
    @Published var draft: [Draft] = [] 

    init() {
        getArray(id: "beers") { (items) in
            items.forEach { (item) in
                self.draft.append(Draft(
                    title: item.fields["title"] as! String,type: item.fields["type"] as! String,description: item.fields["type"] as! String
                ))
            }
        }
    }
}

struct DraftList: View {
    var width: CGFloat = 275
    var height: CGFloat = 200
    @ObservedObject var api = API()
    var body: some View {
            VStack {
             ForEach(api.draft) {item in 
                Spacer()
                Text(item.title)
                    .font(.system(size: 24,weight: .bold))
                    .padding(.horizontal,20)
                    .frame(width: 275,alignment: .leading)
                    .foregroundColor(Color("TextColor"))
    
                ...
             }
            }
            .padding(.horizontal,20)
            .frame(width: width,height: height)
            .background(Color("TileOrangeColor"))
            .cornerRadius(15)
            .shadow(color: Color.black.opacity(0.2),radius: 5,x: 0,y: 5)
        }
    }