I'm trying to set a published variable named allCountries. In my DispatchQueue, it's being set and is actually printing out the correct information to the console. In my content view, nothing is in the array. In the init function on the content view, I'm calling the the function that will fetch the data and set the variable but when I print to the console, the variable is blank. Can someone tell me what I'm doing wrong?
Here is where I'm fetching the data
class GetCountries: ObservableObject {
@Published var allCountries = [Countries]()
func getAllPosts() {
guard let url = URL(string: "apiURL")
else {
fatalError("URL does not work!")
}
URLSession.shared.dataTask(with: url) { data, _, _ in
do {
if let data = data {
let posts = try JSONDecoder().decode([Countries].self, from: data)
DispatchQueue.main.async {
self.allCountries = posts
print(self.allCountries)
}
} else {
DispatchQueue.main.async {
print("didn't work")
}
}
}
catch {
DispatchQueue.main.async {
print(error.localizedDescription)
}
}
}.resume()
}
}
Here's my content view
struct ContentView: View {
var countries = ["Select Your Country", "Canada", "Mexico", "United States"]
@ObservedObject var countries2 = GetCountries()
@State private var selectedCountries = 0
init() {
GetCountries().getAllPosts()
print(countries2.allCountries)
}
var body: some View {
NavigationView {
ZStack {
VStack {
Text("\(countries2.allCountries.count)")}}}