Search code examples
swiftswiftuiios-simulator

How Xcode simulator is fetching data from internet when the internet connection is OFF?


I have created a simple SwiftUI app, which should display a list of songs fetched from iTunes url link:

import SwiftUI
struct Response: Codable {
var results: [Result]
}
struct Result: Codable {
var trackId: Int
var trackName: String
var collectionName: String
}
struct ContentView: View {
@State private var results = [Result]()
var body: some View {
    List(results, id: \.trackId) { item in
        VStack(alignment: .leading) {
            Text(item.trackName)
                .font(.headline)
            Text(item.collectionName)
        }
    }
.onAppear(perform: loadData)
}

   func loadData() {
guard let url = URL(string: "https://itunes.apple.com/search?term=taylor+swift&entity=song") else {
    print("Invalid URL")
    return
}
let request = URLRequest(url: url)
URLSession.shared.dataTask(with: request) { data, response, error in
  if let data = data {
        if let decodedResponse = try? JSONDecoder().decode(Response.self, from: data) {
            DispatchQueue.main.async {
                self.results = decodedResponse.results
            }
        
            return
        }
    }
    print("Fetch failed: \(error?.localizedDescription ?? "Unknown error")")
}.resume()
}
}

When the internet connection on my Mac is On, I am able to fetch the data and load it to the list. I decided to turn it off, then I completely closed/deleted the app from memory then opened it app again and the data was still there. This is very confusing for me, can somebody explain me what is happening, because the code should load the data only when the Wi-Fi is ON, why I am still able to see it when it is OFF?

Short video of my simulator

My question is, why here is gone?


Solution

  • Just try to use .reloadIgnoringLocalCacheData. It worked for me.