【发布时间】:2019-12-03 04:29:02
【问题描述】:
我正在尝试从Rest Api 获取数据以下载并在SwiftUI 的列表视图中呈现。
我想我设法让JSON 正确下载并分配给所有相关的结构,但是当我去构建它时,模拟器的列表视图中没有显示任何内容。
我什至不确定是否需要在其中添加“Enum CodingKeys”。
谁能指出我哪里出错了?
import Foundation
import SwiftUI
import Combine
struct ContentView: View {
@ObservedObject var fetcher = LaunchDataFetcher()
var body: some View {
VStack {
List(fetcher.launches) { launch in
VStack (alignment: .leading) {
Text(launch.mission_name)
Text(launch.details)
.font(.system(size: 11))
.foregroundColor(Color.gray)
}
}
}
}
}
public class LaunchDataFetcher: ObservableObject {
@Published var launches = [launch]()
init(){
load()
}
func load() {
let url = URL(string: "https://api.spacexdata.com/v3/launches")!
URLSession.shared.dataTask(with: url) {(data,response,error) in
do {
if let d = data {
let decodedLists = try JSONDecoder().decode([launch].self, from: d)
DispatchQueue.main.async {
self.launches = decodedLists
}
}else {
print("No Data")
}
} catch {
print ("Error")
}
}.resume()
}
}
struct launch: Codable {
public var flight_number: Int
public var mission_name: String
public var details: String
enum CodingKeys: String, CodingKey {
case flight_number = "flight_number"
case mission_name = "mission_name"
case details = "details"
}
}
// Now conform to Identifiable
extension launch: Identifiable {
var id: Int { return flight_number }
}
struct ContentView_Previews: PreviewProvider {
static var previews: some View {
ContentView()
}
}
【问题讨论】:
-
如果键和结构成员具有相同的名称,则不需要 CodingKeys。如果您将结构成员命名为 camelCased 并添加
convertFromSnakeCase键解码策略,您甚至不需要 CodingKeys。 -
我以为是这样。感谢您的建议。
标签: ios swiftui xcode11 swift5.1 swiftui-list