I have a test app that is supposed to list a bunch of iTunes music records. I have existing lines of code that successfully load data. Now, I'm adding a loading state to them. As a result, I have the following lines code.
import SwiftUI
struct iTunesView: View {
@StateObject var viewModel = iTunesViewModel()
var body: some View {
switch viewModel.state {
case .idle: EmptyView()
case .loading: ProgressView()
case .loaded(let results):
List {
ForEach(results, id: \.self) { result in
Text("\(result.trackId)")
Text(result.trackName)
.lineLimit(0)
}
}
case .failed(let error):
Text(error.localizedDescription)
}
}
}
@MainActor
class iTunesViewModel: ObservableObject {
enum LoadingState {
case idle
case loading
case loaded([iTunesResult])
case failed(Error)
}
@Published var state: LoadingState = .idle
init() {
state = .loading
Task {
await fetchMusic()
}
}
func fetchMusic() async {
guard let url = URL(string: "https://itunes.apple.com/search?term=classical+music&entity=song") else {
state = .failed(URLError(.badURL))
return
}
do {
let urlRequest = URLRequest(url: url, timeoutInterval: 1.0)
let (data, _) = try await URLSession.shared.data(for: urlRequest)
let music = try JSONDecoder().decode(iTunesResponse.self, from: data)
self.state = .loaded(music.results)
print("\(music.results)")
} catch {
state = .failed(error)
}
}
}
struct iTunesResponse: Codable {
let resultCount: Int
let results: [iTunesResult]
}
struct iTunesResult: Codable, Hashable {
var trackId: Int
var trackName: String
var collectionName: String
}
enum iTunesError: Error {
case badURL
case decoding
case invalidHTTPResponse
case badData(statusCode: Int)
case badRequest(statusCode: Int)
case redirection(statusCode: Int)
case server(statusCode: Int)
case error(String)
}
For some reason, the app just shows a spinner although it reaches the print line in the fetchMusci function and print the string data. I wonder what I'm doing wrong? With the code lines above, an app is fully functional except it will show the progress guy, you know? I've made changes after reading this Stack overflow topic. Thanks.