PoolHallJunkie
PoolHallJunkie

Reputation: 1363

Swift: Async method into while loop

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)
            }
        })
    }

Upvotes: 8

Views: 5338

Answers (2)

Moriya
Moriya

Reputation: 7906

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)
        }
    })
}

Upvotes: 20

t4nhpt
t4nhpt

Reputation: 5302

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

Upvotes: 5

Related Questions