I have a list with data from the search. to get data I want to call to await func (swift 5.5) but I get this error:
"Cannot pass function of type '() async -> ()' to parameter expecting synchronous function type"
this is my code:
struct ContentView: View {
@ObservedObject var twitterAPI: TwitterAPI = TwitterAPI()
@State private var searchText = "TheEllenShow" // TheEllenShow
var body: some View {
NavigationView {
VStack{
if twitterAPI.twitterSearchResults?.resultDataVM != nil{
List {
ForEach((twitterAPI.twitterSearchResults?.resultDataVM)!) { item in
Text(item.text)
}
}
.refreshable {
await twitterAPI.executeQuery(userName: searchText)
}
}else{
Text("Loading")
}
Spacer()
}
.searchable(text: $searchText)
.onSubmit(of: .search) {
await twitterAPI.executeQuery(userName: searchText)
}
.navigationTitle("Twitter")
}
.task {
await twitterAPI.executeQuery(userName: searchText)
}
} }
To call asynchronous code from a synchronous code block, you can create a Task
object:
.onSubmit(of: .search) {
Task {
await twitterAPI.executeQuery(userName: searchText)
}
}
You could bounce it over to .task
like this:
@State var submittedSearch = ""
@State var results = []
.onSubmit(of: .search) {
submittedSearch = searchText
}
.task(id: submittedSearch) {
if submittedSearch.isEmpty {
return
}
results = await twitterAPI.executeQuery(userName: submittedSearch)
}
Has the advantage it will be cancelled and restarted if the search changes and also when the underlying UIView disappears.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.