Swift 如何重新加载环境对象

Swift How to reload an Environment-Object

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


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

我会将 init 中的 fetching/loading 数据代码放入函数中。

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

在您的 initButton 中调用该方法,例如 cards.codeToFetchData()