I want to use a async function inside a while loop but the function don't get enough time to finish and the while loop starts again and never ends.
I should implement this problem with increment variable , but what is the solution? thanks a lot.
output loops between "Into repeat" - "Into function"
var condition = true
var userId = Int.random(1...1000)
repeat {
print("Into repeat")
checkId(userId, completionHandler: { (success:Bool) -> () in
if success {
condition = false
} else {
userId = Int.random(1...1000)
}
}) } while condition
func checkId(userId:Int,completionHandler: (success:Bool) -> ()) -> () {
print("Into function")
let query = PFUser.query()
query!.whereKey("userId", equalTo: userId)
query!.findObjectsInBackgroundWithBlock({ (object:[PFObject]?, error:NSError?) -> Void in
if object!.isEmpty {
completionHandler(success:false)
} else {
completionHandler(success:true)
}
})
}
You can do this with a recursive function. I haven't tested this code but I think it could look a bit like this
func asyncRepeater(userId:Int, foundIdCompletion: (userId:Int)->()){
checkId(userId, completionHandler: { (success:Bool) -> () in
if success {
foundIdCompletion(userId:userId)
} else {
asyncRepeater(userId:Int.random(1...1000), completionHandler: completionHandler)
}
})
}
You should use dispatch_group
repeat {
// define a dispatch_group
let dispatchGroup = dispatch_group_create()
dispatch_group_enter(dispatchGroup) // enter group
print("Into repeat")
checkId(userId, completionHandler: { (success:Bool) -> () in
if success {
condition = false
} else {
userId = Int.random(1...1000)
}
// leave group
dispatch_group_leave(dispatchGroup)
})
// this line block while loop until the async task above completed
dispatch_group_wait(dispatchGroup, DISPATCH_TIME_FOREVER)
} while condition
See more at Apple document
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With