【问题标题】:Generic struct 'ObservedObject' requires that 'Video' conform to 'ObservableObject' in SwiftUI通用结构 'ObservedObject' 要求 'Video' 符合 SwiftUI 中的 'ObservableObject'
【发布时间】:2022-01-12 07:46:28
【问题描述】:

我正在尝试调用 API 并将数据填充到 SwiftUI 中的列表中,我是 SwiftUI 的初学者,我正在努力解决提到的错误。 我认为我的数据模型有问题 我已经尝试过在 swift Lnaguage 中进行普通 API 调用的方式,但它看起来并不奏效

这是我得到的错误的图像.. https://i.stack.imgur.com/OpVwh.png

struct testAPIData : Codable,Identifiable {
    public var id: Int?
    let response_code : Int?
    let status : Int?
    let mesagges : String?
    let data_array : testAPIDetails?

    enum CodingKeys: String, CodingKey {

        case response_code = "response_code"
        case status = "status"
        case mesagges = "mesagges"
        case data_array = "data_array"
        case id = "id"
    }

    init(from decoder: Decoder) throws {
        let values = try decoder.container(keyedBy: CodingKeys.self)
        response_code = try values.decodeIfPresent(Int.self, forKey: .response_code)
        status = try values.decodeIfPresent(Int.self, forKey: .status)
        mesagges = try values.decodeIfPresent(String.self, forKey: .mesagges)
        id = try values.decodeIfPresent(Int.self, forKey: .id)
        data_array = try values.decodeIfPresent(testAPIDetails.self, forKey: .data_array)
    }

}
struct testAPIDetails : Codable,Identifiable {
    public var id: Int?
    let video : [Video]?
    let moreinfo : [Moreinfo]?
    let photourl : String?
    let topcontent : String?
    let data : Int?

    enum CodingKeys: String, CodingKey {

        case video = "video"
        case moreinfo = "moreinfo"
        case photourl = "photourl"
        case topcontent = "topcontent"
        case data = "data"
        case id = "id"
    }

    init(from decoder: Decoder) throws {
        let values = try decoder.container(keyedBy: CodingKeys.self)
        video = try values.decodeIfPresent([Video].self, forKey: .video)
        moreinfo = try values.decodeIfPresent([Moreinfo].self, forKey: .moreinfo)
        photourl = try values.decodeIfPresent(String.self, forKey: .photourl)
        topcontent = try values.decodeIfPresent(String.self, forKey: .topcontent)
        id = try values.decodeIfPresent(Int.self, forKey: .id)
        data = try values.decodeIfPresent(Int.self, forKey: .data)
    }

}

struct Video : Codable,Identifiable {
    public var id: Int?
    public var weburl : String?
    public var heading : String?
    public var description : String?
    public var thumbnail : String?
    public var clickableurl : String?

    enum CodingKeys: String, CodingKey {

        case weburl = "weburl"
        case heading = "heading"
        case description = "description"
        case thumbnail = "thumbnail"
        case clickableurl = "clickableurl"
        case id = "id"
    }

    init(from decoder: Decoder) throws {
        let values = try decoder.container(keyedBy: CodingKeys.self)
        weburl = try values.decodeIfPresent(String.self, forKey: .weburl)
        heading = try values.decodeIfPresent(String.self, forKey: .heading)
        description = try values.decodeIfPresent(String.self, forKey: .description)
        id = try values.decodeIfPresent(Int.self, forKey: .id)
        thumbnail = try values.decodeIfPresent(String.self, forKey: .thumbnail)
        clickableurl = try values.decodeIfPresent(String.self, forKey: .clickableurl)
    }

}



这是我的课

class Videos: NSObject,ObservableObject {
    @Published var videoDataArray:[Video] = [Video]()
    override init() {
        if let StartEventURL = URL.init(string:"<<MYAPI>>") {
            let parameters = ["contenttype":"1"]
            var request = URLRequest(url: StartEventURL)
            request.httpMethod = "POST"
            request.setValue("application/json", forHTTPHeaderField: "Content-Type")
            do{
                request.httpBody = try JSONSerialization.data(withJSONObject: parameters)
                AF.request(request).responseData{response in
                    if let data = response.data{
                        do{
                          _ = try JSONSerialization.jsonObject(with: data, options: [])
                            let decoder = JSONDecoder()
                            let StartEventResponse = try decoder.decode(testAPIData.self, from: data)
                            DispatchQueue.main.async {
                                self.videoDataArray = (StartEventResponse.data_array?.video)!
                            }
                        } catch {
                            print(error)
                            DispatchQueue.main.async {
                                //Alert
                            }
                        }
                    }
                }.resume()
            }catch let error {
                print("Error : \(error.localizedDescription)")
            }
        }

    }
}




最后是我的内容在这里查看

struct ContentView: View {
    @ObservedObject var videoObject = Video() "I'm getting the error here"
    
    init() {
       
       }
    @State private var selection = 0
    @State private var showingAlert = false
    var body: some View {
        NavigationView {
            ZStack(alignment: .topTrailing) {
                VStack {
                    Text("YOUR PRIMARY CARE PROVIDER").font(.title2).fontWeight(.bold).foregroundColor(Color.gray).multilineTextAlignment(.center).padding()
                    Spacer()
                    TabView(selection: $selection) {
                        List(description, id: \.self) { description in
                              Text(description)
                            }
                        .tabItem {
                            Image(systemName: "house.fill")
                            Text("Home")
                        }.tag(1)
                    }.accentColor(.blue)
                    .onAppear() {
                        UITabBar.appearance().barTintColor = .white
                    }
                }.ignoresSafeArea(.container, edges: .bottom)
            }.navigationTitle("My Health")
            
        }
    }
   
}


struct ContentView_Previews: PreviewProvider {
    static var previews: some View {
        Group {
            ContentView()
        }
    }
}

【问题讨论】:

  • 最好为类型使用更独特的名称以避免无意的误用(尤其是在代码完成时)。
  • 注意点,谢谢 :-)

标签: struct swiftui swiftui-list decodable swift-class


【解决方案1】:

根据您的代码,它应该是Videos

struct ContentView: View {
    @ObservedObject var videoObject = Videos()  // << here !!
...

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2020-03-21
    • 2021-11-01
    • 2021-01-05
    • 2020-03-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多