I've on my app Apollo client to make request GraphQL to an API. I want put my requests in a class like that:
class requestAPI {
static func checkUsername(nameUser: String!) -> Bool{
var res: Bool = false
Network.shared.apollo.fetch(query: CheckUsernameQuery(username: nameUser)) { result in
switch result {
case .success(let response):
res = response.data?.checkUsername
print(“Reponse: \(response.data?.checkUsername)“)
case .failure(let error):
print(“Error: \(error)“)
}
}
return res
}
}
So i just want to get value response.data.checkUsername and return it, but res is always false because i think that the fetch is asynch. So what can i do to get the value of response.data.checkUsername (it's a Bool) and return it ?
Thanks all
Cross-posting from the Apollo Spectrum Chat:
Hi! You'll need to use a completion closure like this:
static func checkUsername(nameUser: String!, completion: @escaping (Bool) -> Void) {
Network.shared.apollo.fetch(query: CheckUsernameQuery(username: nameUser)) { result in
switch result {
case .success(let response):
res = response.data?.checkUsername ?? false
completion(res)
case .failure(let error):
// whatever error handling you want to do
}
}
The closure is a function that you pass as a parameter, and then you call it with the result asynchronously rather than returning the result directly from the function.
This is a pretty common pattern in Swift - I'd recommend reading up on it. The Swift doc on closures is exceptionally long and probably a little too detailed as a starting point, but it covers a ton of stuff. I think a better intro-level piece is John Sundell's article about closures.