0

我正在尝试从 a 中获取数据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()
    }
}
4

3 回答 3

0

首先,我尝试找出您的代码的哪个错误并识别某处响应数据的launch.details为null。所以我只是将此属性标记为可选并且它可以工作。

有关更多详细信息,您可以参考以下代码:

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

在捕获线,获取错误消息以确切了解发生了什么

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 {
                        print(decodedLists)
                        self.launches = decodedLists
                    }
                }else {
                    print("No Data")
                }
            } catch let parsingError {
                print ("Error", parsingError)
            }

        }.resume()
    }

希望这有帮助!

于 2019-12-03T08:24:01.553 回答
0

控制台中有任何消息吗?我认为您需要在 .plist 中添加 NSAppTransportSecurity>NSAllowsArbitraryLoads>YES

传输安全已阻止明文 HTTP

于 2019-12-03T09:48:53.360 回答
0

在 Trai Nguyen 的帮助下,我设法让模拟器显示数据。

我所缺少的只是确保名为“详细信息”的变量具有可选属性(通过添加“?”) - 就像这样:

 public var details: String?

然后确保当我在视图中呈现文本时,如果返回为空,我必须给它一个值来插入 - 就像这样:

Text(launch.details ?? "No Data Found")

这是对我有用的完整代码:

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 ?? "No Data Found")
                        .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 {
                        print(decodedLists)
                        self.launches = decodedLists
                    }
                }else {
                    print("No Data")
                }
            } catch let parsingError {
                print ("Error", parsingError)
            }

        }.resume()
    }
}

struct launch: Codable {
    public var flight_number: Int
    public var mission_name: String
    public var details: String?
}

/// Now conform to Identifiable
extension launch: Identifiable {
    var id: Int { return flight_number }
}


struct ContentView_Previews: PreviewProvider {
    static var previews: some View {
        ContentView()
    }
}
于 2019-12-03T11:00:10.340 回答