func runQuery() -> (String){
appSyncClient?.fetch(query: ListTodosQuery(), cachePolicy: .returnCacheDataAndFetch) {(result, error) in
if error != nil {
print(error?.localizedDescription ?? "")
return
}
print("Query complete.")
result?.data?.listTodos?.items!.forEach { print(($0?.name)! + " " + ($0?.description)!) }
}
return the string
}
It is the AWS AMPLIFY tutorial code. It only prints out the result from the DB ($0?.name, etc...)
.
However, I want to return the value of $0?.name
.
When I try to assign or set a var to bring the parameter out from the function.
It's either returns nothing or it does not allow me to return a value.
Any idea?
fetch
method execute asynchronously. Asynchronous function can not return a result on function return.
Here I concatenate $0?.name
s and use blank space as separators.
func runQuery(completionHandler: @escaping (String) -> Void) {
appSyncClient?.fetch(query: ListTodosQuery(), cachePolicy: .returnCacheDataAndFetch) {(result, error) in
if error != nil {
print(error?.localizedDescription ?? "")
completionHandler("")
return
}
print("Query complete.")
var sampleString = ""
result?.data?.listTodos?.items!.forEach {
print(($0?.name)! + " " + ($0?.description)!)
sampleString += $0?.name + " "
}
completionHandler(sampleString)
}
}
func callQuery() {
runQuery(completionHandler: { (result) in
// do what you want
print(result)
})
}