如何在swiftUI中显示JSON数据

时间:2019-11-15 18:44:17

标签: json swift swiftui urlsession

我在SwiftUI中显示JSON数据时遇到问题,我从当前正在搜索歌曲的Genius API获取数据,并且可以确认是否正确提取了数据;示例我可以打印出结果的标题:

enter image description here

这就是我获取数据的方式

class NetworkManager: ObservableObject {
    var objectWillChange = PassthroughSubject<NetworkManager, Never>()

    var fetchedSongsResults = [hits]() {
        willSet {
            objectWillChange.send(self)
        }
    }

    init() {
        fetchSongs()
    }

    func fetchSongs() {
        guard let url = URL(string: "https://api.genius.com/search?q=Sia") else { return }
        var urlRequest = URLRequest(url: url)
        urlRequest.setValue("Bearer TOKEN", forHTTPHeaderField: "Authorization")

      URLSession.shared.dataTask(with: urlRequest) {data, response, error in
            guard let data = data else { return }
            //print(String(decoding: data, as: UTF8.self))
            let songs = try! JSONDecoder().decode(feed.self, from: data)
            DispatchQueue.main.async {
                self.fetchedSongsResults = songs.response.hits

            }
        }.resume()
    }
}

因此,当我获取数据时,我将其保存到变量fetchedSongsResults中,这看起来是正确的,但是出于某种原因,例如,当我尝试打印计数时,它说我为空,而且我无法使用a循环遍历fetchedSongsResults list或ForEach,这就是方法,(我相信这是因为我没有使模型可识别),我试图打印fetchedSongsResults的计数,

这是在体外初始化的(只是您知道)

@State var networkManager = NetworkManager()

这是在体内

Text("\(networkManager.fetchedSongsResults.count)")

如果您想知道解码JSON数据时我的结构如何,那么就在这里

struct feed: Codable {
   var meta: meta
   var response: response
}

struct meta: Codable {
   var status: Int
}

struct response: Codable {
   var hits: [hits]
}

struct hits: Codable {
   var index: String
   var type: String
   var result: song
}

struct song: Codable, Identifiable {
   var id: Int
   var header_image_thumbnail_url: String
   var url: String
   var title: String
   var lyrics_state: String
   var primary_artist: artist

}

struct artist: Codable {
   var name: String
}

1 个答案:

答案 0 :(得分:0)

尝试:@ObservedObject var networkManager = NetworkManager()。