1

我想在我的视图中添加一个按钮来加载更多数据。在我的环境对象中,数据是通过 API 随机生成的。如何重新加载我的 Environment 对象以获取新项目。下面的代码应该清楚。提前致谢


class observer : ObservableObject{
    @Published var shows = [stacks]()
 
    @Published var last = -1
    var results = [Result1]()
    init(){
        let number = Int.random(in: 1...35)
        print("das ist dier etste radodm nube: \(number)")

        let endnumber = number + 8
        print("das ist dier etste radodm nube: \(endnumber)")
                for n in number...endnumber{

                guard let url = URL(string:"https://api.themoviedb.org/3/discover/tv?api_key=3ed2bd15f916d0e3fbb77c193bf33b61&language=de-DE&region=DE&with_networks=213&page=\(n)" ) else {
                    print("Invalid URL")
                    return
                }
                let request = URLRequest(url: url)
                URLSession.shared.dataTask(with: request) { data, response, error in
        
                    if let data = data {
        
                        if let decodedResponse = try? JSONDecoder().decode(Response.self, from: data) {
        
                            DispatchQueue.main.async {
        
                                self.results = decodedResponse.results
                                for i in self.results{
                                    self.shows.append(stacks(id: "\(i.id)", name: i.name, typ: "Serie", status: "",overview: i.overview, vote: "\(i.vote_average)", image: i.poster_path, swipe: 0, degree: 0, commercal: "no"))
                                }
                                self.shows.shuffle()
                            }
                            return
                        }
                    }
                    print("Fetch failed: \(error?.localizedDescription ?? "Unknown error")")
                    }.resume()
                }
     } 
}


struct View: View {
    @EnvironmentObject var cards : observer
    
    var body: some View {
              VStack{
            Button(action: {
               //reload
            }){
             Text("reload")
            }
        }
4

1 回答 1

1

我会将获取/加载数据的代码放在init函数中。

func codeToFetchData() {
    //Code from your init
}

例如在你init和你的调用那个方法Buttoncards.codeToFetchData()

于 2020-11-12T21:42:36.240 回答