I am using Xcode 8.2.1 for an IOS app, the latest usergrid SDK 2.1.3. I am having troubles with the best way to make multiple calls to usergrid to validate data before finally creating a new entity. The problem is the code is continuing before the validation on 1 or more users is complete. The validation MUST happen before I have add the users to the entity that I want to create.
Usergrid has the following performRequest for all Data calls :
func performRequest(_ request:UsergridRequest, completion:UsergridResponseCompletion?) {
session.dataTask(with: request.buildNSURLRequest()) { [weak self] (data, response, error) -> Void in
let usergridResponse = UsergridResponse(client:self?.client, data: data, response: response as? HTTPURLResponse, error: error as NSError?)
DispatchQueue.main.async {
completion?(usergridResponse)
}
}.resume()
}
}
The completion handler returns too late. (Very common theme).
I want to do this : - with a list of users, check whether they exist already. Usergrid API: UsergridUser.checkAvailable - Add user if they don't exist - Create a new group - Add the users to the new group
static func checkAvailabilty(username:String, email:String, completion: @escaping (AuthResult) -> ()) {
//
// other checking
// error: UsergridResponseError?
UsergridUser.checkAvailable(email, username: username, completion: { (error,avail) -> Void in
if error != nil {
completion(.failure(error))
} else {
completion(.success(avail))
}
})
}
And in the View controller :
UsergridManager.checkAvailabilty(username: "jim", email: "") { result in
switch result {
case .success(let granted) :
if granted {
print("user is available")
} else {
print("user is NOT available")
}
case .failure(let error): print(error?.errorDescription)
}
}
The View controller continue's before I know whether the user is available. Should the performRequest be changed? I have attempted DispatchGroup, attempted a Dispatch.main.sync - but would like another option rather than nesting the completion handlers for all these calls.