I have the following lines of code to list some music titles from iTunes music. The code is 100% reproducible.
import SwiftUI
struct MusicView: View {
@StateObject var viewModel = ViewModel()
var body: some View {
MusicListView(viewModel: viewModel)
}
}
struct MusicListView: View {
@ObservedObject var viewModel: ViewModel
var body: some View {
NavigationView {
List(viewModel.results, id: \.self) { result in
VStack(alignment: .leading) {
Text("Track ID: \(result.trackId)")
Text("Track name: \(result.trackName)")
}
}
.task {
do {
try await viewModel.fetchMusic()
} catch SessionError.badURL {
print("Bad URL")
} catch SessionError.invalidHTTPResponse {
print("Invalid HTTP response")
} catch SessionError.error(let err) {
print("Error: \(err)")
} catch {
print("\(error.localizedDescription)")
}
}
.navigationTitle("Music")
}
}
}
class ViewModel: ObservableObject {
@Published var results: [Result] = []
func fetchMusic() async throws {
guard let url = URL(string: "https://itunes.apple.com/search?term=classical+music&entity=song") else {
throw SessionError.badURL
}
let urlRequest = URLRequest(url: url, timeoutInterval: 0.00) // <<<<<<<<<<<<<
URLSession.shared.dataTask(with: urlRequest) { data, response, error in
do {
guard let data = data, error == nil else {
throw SessionError.noData
}
guard let httpResponse = response as? HTTPURLResponse else {
throw SessionError.invalidHTTPResponse
}
switch httpResponse.statusCode {
case 200:
let res = try JSONDecoder().decode(Response.self, from: data)
DispatchQueue.main.async {
self.results = res.results
}
case 400...499:
throw SessionError.badURL
default:
fatalError()
break
}
} catch {
print(error.localizedDescription)
}
}
.resume()
}
}
struct Response: Codable {
let resultCount: Int
let results: [Result]
}
struct Result: Codable, Hashable {
var trackId: Int
var trackName: String
var collectionName: String
}
enum SessionError: Error {
case badURL
case noData
case decoding
case invalidHTTPResponse
case badRequest(statusCode: Int)
case redirection(statusCode: Int)
case server(statusCode: Int)
case error(String)
}
As you see in the screenshot, I get some music titles listed.
My question is why I get a list when in fact I have the URLRequest's timeout value set to 0.00? I haven't run it with an actual device. As far as I use an iPhone simulator, regardless of the timeout value that I set, I get data downloaded. I wonder why?
Muchos thankos for reading