I am following tutorials to understand SwiftUI, and specifically how to call an API when a view appears.
I saw this:
List(results, id: \.trackId) { item in
ListRow(item)
}
.task {
// perform API here
}
But as my app targets iOS 14, I get this error:
'task(priority:_:)' is only available in iOS 15.0 or newer
So what could I do instead? Thank you for your help
CodePudding user response:
import SwiftUI
struct ContentView: View {
@State var results = [TaskEntry]()
var body: some View {
List(results, id: \.id) { item in
VStack(alignment: .leading) {
Text(item.title)
}
// this one onAppear you can use it
}.onAppear(perform: loadData)
}
func loadData() {
guard let url = URL(string: "https://jsonplaceholder.typicode.com/todos") else {
print("Your API end point is Invalid")
return
}
let request = URLRequest(url: url)
URLSession.shared.dataTask(with: request) { data, response, error in
if let data = data {
if let response = try? JSONDecoder().decode([TaskEntry].self, from: data) {
DispatchQueue.main.async {
self.results = response
}
return
}
}
}.resume()
}
}