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)
}
}
}
You're kind of mixing up two approaches here: completion handlers and return values, like seen with async/await. Since your data fetch is using a completion handler, you can follow this route and add a completion closure parameter to the getData function which can then be called when you get the data.
Here's an example of what this would look like:
private func getData(from url: String, completion: @escaping (Response) -> Void) {
let task = URLSession.shared.dataTask(with: URL(string: url)!) { data, response, error in
...
completion(json)
}
task.resume()
}
// in SwiftUI View
.onAppear {
getData(from: url) { results = $0 }
}