Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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)
            }
        })
    }
like image 909
PoolHallJunkie Avatar asked Oct 28 '15 01:10

PoolHallJunkie


2 Answers

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)
        }
    })
}
like image 136
Moriya Avatar answered Nov 06 '22 15:11

Moriya


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

like image 23
t4nhpt Avatar answered Nov 06 '22 13:11

t4nhpt