Hello, I want to fetch json data from an api and then display it in a view. It is showing me an error ("Missing return in global function expected to return 'Response'") in the end of the function. How can I return the fetched data and where should I put the return statement?
private func getData(from url: String) -> Response {
let task = URLSession.shared.dataTask(with: URL(string: url)!, completionHandler: {
data, response, error in
guard let data = data, error == nil else {
print("Something went wrong")
return
}
var result: Response?
do {
result = try JSONDecoder().decode(Response.self, from: data)
}
catch {
print("failed to convert \(error)")
}
guard let json = result else {
return
}
print(json)
})
task.resume()
}
I call the function this way:
struct ShowData: View {
@State var results: Response
var body: some View {
Text("Hello world").onAppear {
results = getData(from: url)
}
}
}