当试图解析来自SwiftUI中REST端点的一些数据时,我很难正确地呈现到列表中。
在下面的示例中,我的列表需要精确的数组位置来呈现结果,所以如果没有[0]等,它就不会显示任何内容。
我习惯于在JavaScript中使用for循环来解决这种类型的问题,并对其进行迭代以将每个数组位置分配给[i],但是在SwiftUI中,我很难做到同样的事情。
我认为如何处理嵌套的JSON对象可能是个问题,但现在开始。我也相信,这可能是一个简单的解决方案,我只是在这里模糊。
我已经创建了一个测试端点,如果您需要在本地运行它,可以从中获取它(这已经在下面的示例中了)。
来澄清我想在这里做什么。我想在数组上迭代以引用(例如) Text(item.objects.title),而不必指定我要寻找的数组中的哪一项。遗憾的是,使用ForEach并不有效,因为List(viewModel.items, id: \.self) { item in }实际上是在复制ForEach循环,而且也不起作用。
模型
struct ObjectResponse: Hashable, Decodable {
let objects: [Object]
}
struct Object: Hashable, Decodable {
let slug: String
let title: String
let metadata: Metadata
}
struct Metadata: Hashable, Decodable {
let published: String
let url: String
let snippet: String
let read: Bool
}ViewModel
class ContentViewModel: ObservableObject {
@Published var items: [ObjectResponse] = []
func fetchData() {
let api = "https://api.cosmicjs.com/v2/buckets/a5e294b0-55ee-11ec-942e-ef0a04148eb7/objects?pretty=true&query=%7B%22type%22%3A%22bookmarks%22%7D&read_key=fufvo5ceSy1W88afkchDIRjYrUIzErPw9YzcW2vQV1SxKqjNHo&limit=20&props=slug,title,content,metadata,"
guard let url = URL(string: api) else { return }
URLSession.shared.dataTask(with: url) { (data, response, error) in
do {
if let data = data {
let result = try JSONDecoder().decode(ObjectResponse.self, from: data)
DispatchQueue.main.async {
self.items = [result]
/* Prints out everything nicely
result.objects.forEach {
print($0.title)
}
*/
}
} else {
print("No data")
}
} catch (let error) {
print(error)
}
}.resume()
}
}内容视图
struct ContentView: View {
@ObservedObject var viewModel = ContentViewModel()
var body: some View {
NavigationView {
List(viewModel.items, id: \.self) { item in
VStack(alignment: .leading) {
Text(item.objects[0].title) // Requires me to provide array position
}
}
.navigationTitle("Bookmarks")
}
.onAppear(perform: {
viewModel.fetchData()
})
}
}示例JSON响应
{
"objects": [
{
"slug": "the-navigation-bar-isnt-hidden-as-expected-in-swiftui",
"title": "The Navigation Bar Isn’t Hidden as Expected in SwiftUI",
"content": null,
"metadata": {
"published": "28 Nov 2021 at 16:30",
"url": "https://betterprogramming.pub/swiftui-navigationbar-is-not-really-hidden-as-you-expect-785ff0425c86",
"snippet": "",
"read": true
}
},
{
"slug": "hey-facebook-i-made-a-metaverse-27-years-ago",
"title": "Hey, Facebook, I Made a Metaverse 27 Years Ago",
"content": null,
"metadata": {
"published": "28 Nov 2021 at 21:39",
"url": "https://www.theatlantic.com/technology/archive/2021/10/facebook-metaverse-was-always-terrible/620546/",
"snippet": "Michel Baret / Gamma-Rapho / Getty In a booth at Ted’s Fish Fry, in Troy, New York, my friend Daniel Beck and I sketched out our plans for the metaverse. ",
"read": true
}
},
{
"slug": "when-big-tech-buys-small-tech-benedict-evans",
"title": "When big tech buys small tech — Benedict Evans",
"content": null,
"metadata": {
"published": "28 Nov 2021 at 21:39",
"url": "https://www.ben-evans.com/benedictevans/2021/11/12/when-big-tech-buys-small-tech",
"snippet": "Acquisitions are a big part of the discussion around competition in tech today, and a big set of questions. It’s easy to say that we wouldn’t let Amazon buy Zappos or Google buy DoubleClick again, but everyone’s favourite puzzle is Instagram. ",
"read": false
}
}
],
"total": 171,
"limit": 3
}发布于 2021-12-05 20:40:12
好了,解决了,多亏了jnpdx的一点帮助。需要通过ForEach循环进一步钻入数组,如下所示:
List(viewModel.items, id: \.self) { item in
ForEach(item.objects, id: \.self) { bookmark in
VStack(alignment: .leading) {
Text(bookmark.title)
}
}
}https://stackoverflow.com/questions/70236719
复制相似问题