【问题标题】:How to using the fetched data in swiftUI如何在 swiftUI 中使用获取的数据
【发布时间】:2021-04-13 09:42:25
【问题描述】:

我目前正在开发一个 IOS 应用程序,我正在尝试使用获取的 json 数据设计一个轮播。这就是我获取目标 json 数据的方式。

class loadDate: ObservableObject {
    @Published var todos = [Result]()
    
    init() {
        let url = URL(string: "https://api.themoviedb.org/3/movie/now_playing?api_key=<api_key>&language=en-US&page=1")!
        URLSession.shared.dataTask(with: url) { data, response, error in
            // step 4
            if let data = data {
                if let decodedResponse = try? JSONDecoder().decode(Response.self, from: data) {
                   
                    DispatchQueue.main.async {
                       
                        self.todos = decodedResponse.results
                    }

                    // everything is good, so we can exit
                    return
                }
            }

            
            print("Fetch failed: \(error?.localizedDescription ?? "Unknown error")")
        }.resume()
    }
    
 }

看起来我只能在列表视图中使用数据,例如,

    struct ContentView: View {
    @ObservedObject var fetch = loadDate()
    var body: some View {
        HStack {
            
            List(fetch.todos) { item in
                HStack {
                    VStack(alignment: .leading) {
                        Text(item.title)
                            .font(.headline)

                        Text(item.poster_path)
    //
                    }
                }

            }
            
        }
        
    }
    
}

在此列表视图中,我可以访问所有元素,例如使用 fetch.todos[0].title。但是,如果在列表视图之外,fetch.todos[0].title 会失败,有人可以就如何使用列表视图之外的数据提供一些建议。

【问题讨论】:

  • 您想在 fetch.todos 的列表之外使用什么?只是任何随机元素或用户选择的东西?

标签: swift swiftui


【解决方案1】:

您应该提供一个工作示例。 (https://stackoverflow.com/help/minimal-reproducible-example)

但是如果todos 是一个空数组,fetch.todos[0].title 总是会失败。因此,当您需要直接访问待办事项时,您可以使用类似这样的东西

Group {
    if fetch.todos.count > 0 {
        Text("Title of first todo \(fetch.todos[0].title)")
    } else {
        Text("Todos are empty")
    }
}

【讨论】:

    【解决方案2】:

    试试这个:

    class loadDate: ObservableObject {
        @Published var todos : Result? = nil // Step 1
        
        // ...
     }
    
    struct ContentView: View {
    
        @ObservedObject var fetch = loadDate()
    
        var body: some View {
            HStack {
                if let todos = fetch.todos {
                    VStack{
                        Text(todos.title)
                            .font(.headline)
                        Text(todos.poster_path)
                    }
                }
            }
        }
    }
    

    https://stackoverflow.com/a/66695683/14287797

    【讨论】:

      猜你喜欢
      • 2020-01-25
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-05-15
      • 2022-07-07
      • 2022-12-31
      • 2020-07-19
      • 2022-01-04
      相关资源
      最近更新 更多