【问题标题】:(3) Errors when calling data from API using Contentful & SwiftUI(3) 使用 Contentful & SwiftUI 从 API 调用数据时出错
【发布时间】:2020-09-23 10:33:14
【问题描述】:

请原谅我,因为我对 SwiftUI 非常陌生...我正在尝试从 CMS 中提取数据并将其放入我的应用程序中,但是每次尝试检索和放置数据时都会引发三个错误...

错误在“api.beers.title”、“api.beers.type”和“api.beers.description”部分突出显示。

错误

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

API 调用代码

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
                ))
            }
        }
    }
}
struct LandingPageView: View {
        var body: some View {
            VStack {
                VStack {
                    Text("Problem Solved")
                    Text("Brewing Company")
                }
                .font(.system(size: 24, weight: .bold))
                .multilineTextAlignment(.center)
                .foregroundColor(Color("TextColor"))

                VStack {
                    Text("NEWS & EVENTS")
                        .font(.title)
                        .fontWeight(.bold)
                        .padding(.top, 40)
                        .foregroundColor(Color("TextColor"))

                    NewsTile()
                    
                    Text("On Draft" .uppercased())
                        .font(.title)
                        .fontWeight(.bold)
                        .padding(.top)
                        .foregroundColor(Color("TextColor"))

                    ScrollView(.horizontal, showsIndicators: false) {
                        HStack(spacing: 20) {
                            ForEach(draftData) { item in
                                GeometryReader { geometry in
                                    DraftList(beer: item)
                                        .rotation3DEffect(Angle(degrees: Double(geometry.frame(in: .global).minX - 30) / -20), axis: (x: 0, y: 10.0, z: 0))
                                }
                                .frame(width: 275, height: 200)
                                
                            }
                        }
                    .padding(.leading, 30)
                    .padding(.trailing, 30)
                }
            }
            .frame(width: 400, height: 850)
            .background(Color("PageBackground"))
            .edgesIgnoringSafeArea(.all)
            
        }
    }
}


struct DraftList: View {
    var width: CGFloat = 275
    var height: CGFloat = 200
    
    @ObservedObject var api = API()
    var beer: Draft
    
    var body: some View {
        VStack {
            Spacer()
            Text(api.beers.title)
                .font(.system(size: 24, weight: .bold))
                .padding(.horizontal, 20)
                .frame(width: 275, alignment: .leading)
                .foregroundColor(Color("TextColor"))
            
            Text(api.beers.type .uppercased())
                 .font(.system(size: 14, weight: .bold))
                 .frame(maxWidth: .infinity, alignment: .leading)
                 .padding(.horizontal, 20)
            
            Text(api.beers.description)
                .font(.system(size: 12))
                .padding(.horizontal, 20)
                .padding(.top, 10)
            Spacer()
            HStack {
//                Add OnTapGesture to bring to full view + cart options.
                Text("Click To Add To Cart")
                    .font(.footnote)
                Image(systemName: "cart")

            }
            .padding(.bottom)

            
        }
        .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)

        
    }
}

【问题讨论】:

    标签: swiftui contentful contentful-api


    【解决方案1】:
    1. 您的草稿是数组,您可以通过索引访问,例如 Text(api.draft[0].title)
    2. @Published var 草稿:[Draft] = draftData 而不是@Published var 草稿:[Draft] = []

    更新:

    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)
            }
        }
    

    【讨论】:

    • 那么,如果我不想让第一个索引为 [0],我需要迭代索引正确吗?
    • 是的。你需要 foreach 数组,有点 foreach(draft){ item in Text(item.title) ... }
    • 谢谢。我能够获得回报,但它引发了一个新错误... 2020-09-22 22:18:26.945306-0400 PSBC[2691:4738524] 致命错误:在展开可选值时意外发现 nil:文件 /Users/ rob/Desktop/SwiftProjects/PSBC/PSBC/API.swift,第 38 行
    • 这可能有帮助吧!大声笑我的错误类型:item.fields["type"] as!字符串,
    • 我认为需要检查客户端数组是否有 ["type"] 字段或者可以像这种类型:(item["type"] as!String?) ?? ""
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2022-01-22
    • 1970-01-01
    • 2022-11-17
    • 1970-01-01
    • 2023-02-20
    • 2020-08-20
    相关资源
    最近更新 更多