Trying to understand API calls in SwiftUI, I got some doubt about environmentObject.Here, I have a file Network.swift which contains a method to get Users. So I create an environmentObject on my ProjectNameApp.swift file (see code).But this is my question:
Let's say I have an another file Products.swift containing methods related to the products API. How I would set it in my ProjectNameApp.swift file ?
// Network.swift
import SwiftUIclass Network: ObservableObject {
@Published var users: [User] = [] func getUsers() {
guard let url = URL(string: "https://jsonplaceholder.typicode.com/users") else { fatalError("Missing URL") } let urlRequest = URLRequest(url: url) let dataTask = URLSession.shared.dataTask(with: urlRequest) { (data, response, error) in
if let error = error {
print("Request error: ", error)
return
} guard let response = response as? HTTPURLResponse else { return } if response.statusCode == 200 {
guard let data = data else { return }
DispatchQueue.main.async {
do {
let decodedUsers = try JSONDecoder().decode([User].self, from: data)
self.users = decodedUsers
} catch let error {
print("Error decoding: ", error)
}
}
}
} dataTask.resume()
}
}
// ProjectNameApp.swift@main
struct ProjectNameApp: App {
var network = Network() var body: some Scene {
WindowGroup {
ContentView()
.environmentObject(network)
}
}
}
Would be the right implementation something like this ? For each API group a new environmentObject ?
// ProjectNameApp.swift@main
struct ProjectNameApp: App {
var network = Network()
var product = Product() var body: some Scene {
WindowGroup {
ContentView()
.environmentObject(network)
.environmentObject(product)
}
}
}
Thank you