In SwiftUI, I call an API in a function. Then, I call that function somewhere else - the function allows me to temporarily save the API data to a local variable ONLY in that specific block of code.
What I need is a way to save the data outside of a block, because I'll use this variable a lot, and I need that data in order to specify different API calls later in the code. Everything I've researched indicates this is not possible.
Example API Call:
func fetchTeamData(String: String, completion: @escaping (TeamStructure)->())
{
let userURL = "x" + String
guard let url = URL(string: userURL) else { return }
URLSession.shared.dataTask(with: url)
{data, _, _ in
self.teams = try! JSONDecoder().decode(TeamStructure.self, from: data!)
DispatchQueue.main.async
{
completion(self.teams)
}
}.resume()
}
Example function call and my problem:
.onAppear()
{
APICaller.fetchTeamData(String: "")
{(teams) in
self.requestedTeam = teams
print(requestedTeam) //full dataset in this variable, I need this data
}
print(requestedTeam) //data is now gone
}
I've tried putting various functions/variables in an init block, but hit same issue where it becomes empty.
I've tried calling functions within the API Call method, but when I send the variable out, it's empty.
I've tried doing more complex data logic inside my view, nesting calls and loops, but I always hit a point where it goes "Hey, this is a view - the thing you're doing isn't allowed here".